Swift-automatically calculates the width and height of a string

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.