Dynamic determination of Uilabel width and height based on character length

Source: Internet
Author: User

IOS7 uses the following methods

-(cgsize) sizewithattributes: (nsdictionary *) attrs;


Alternative to obsolete iOS6 -(cgsize) Sizewithfont: (uifont *) Font method

1 //ios7_api_ dynamically determine label width based on word count2 3     4     //sets the font of the label Helveticaneue Courier5Uifont *fnt = [Uifont fontwithname:@"Helveticaneue"Size24.0f];6_namelabel.font =fnt;7     //get nsstring size according to the font8Cgsize size =[_namelabel.text sizewithattributes:[nsdictionary dictionarywithobjectsandkeys:fnt,nsfontattributename, Nil]] ;9     //the H of the nameTenCGFloat Nameh =Size.Height; One     //W of the name ACGFloat Namew =Size.width; -_namelabel.frame = CGRectMake (0,0, Namew,nameh);

IOS7 uses the following method BoundingRectWithSize:options:attributes:context: instead of Sizewithfont in obsolete iOS6 : Constrainedtosize:linebreakmode: method

1 //4, based on the content of the text, dynamically determine the contents of the frame2     3     //width W4CGFloat contentw = self.bounds.size.width-_content.frame.origin.x-Kmargin;5     //the font of the label Helveticaneue Courier6Uifont *fnt = [Uifont fontwithname:@"Helveticaneue"Size18.0f];7_content.font =fnt;8_content.numberoflines =0;9_content.linebreakmode =nslinebreakbywordwrapping;Ten     //IOS7 replaces SizeWithFont:constrainedToSize:lineBreakMode in obsolete iOS6 using the following methods: OneCGRect tmprect = [_content.text boundingrectwithsize:cgsizemake (CONTENTW, +) Options:nsstringdrawinguseslinefragmentorigin attributes:[nsdictionary dictionarywithobjectsandkeys:fnt, Nsfontattributename, nil] context:nil]; A      -     //height H -CGFloat Contenth =TmpRect.size.height; theNSLog (@"adjusted display width:%f, display height:%f"contentw,contenth); -_content.frame = CGRectMake (0,0, Contentw,contenth);

Dynamic determination of Uilabel width and height based on character length

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.