Write a method to inherit a string
Automatic text wrapping and width control
Extension String {
func textsizewithfont (font: uifont, constrainedtosize size:cgsize), cgsize {
var textSize:cgsize!
if cgsizeequaltosize(size, Cgsizezero) {
let attributes = nsdictionary(Object:font, Forkey: nsfontattributename)
TextSize = self. Sizewithattributes(Attributes as!) [string : anyobject] as [string : anyobject])
} Else {
let option = nsstringdrawingoptions. Useslinefragmentorigin
let attributes = nsdictionary (Object:font, Forkey: Nsfontattributename)
let stringrect = self. Boundingrectwithsize(Size, options:option, attributes:attributes as!) [string : anyobject] as [string : anyobject], context: nil)
TextSize = Stringrect. size
}
return textSize
}
}
Usage:
Let projecttext="I am a string, to calculate my height ";
let projectsize=sizewithtext(Projecttext, maxSize: cgsizemake( ), font: uifont. Systemfontofsize(+));
let comprojectw:cgfloat=projectsize. width;
let comprojecth:cgfloat=projectsize. Height;
Remember to add a uilable in the computed string
Uilable.font=uifont.systemfontofsize (14);
Show several lines
Uilable. NumberOfLines=1;
Uilable. frame = CGRectMake(comprojectw, comprojecth);
Swift-automatically calculates the width and height of a string