IOS-dynamically calculates the text width to define the frame size of the control ., Ios-frame

Source: Internet
Author: User

IOS-dynamically calculates the text width to define the frame size of the control ., Ios-frame

// Dynamically calculates the size occupied by the text based on the uploaded text content, text size, and maximum size.

-(CGSize) labelAutoCalculateRectWith :( NSString *) text FontSize :( CGFloat) fontSize MaxSize :( CGSize) maxSize

{

NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];

ParagraphStyle. lineBreakMode = NSLineBreakByWordWrapping;

NSDictionary * attributes =@{ NSFontAttributeName: [UIFont systemFontOfSize: fontSize], NSParagraphStyleAttributeName: paragraphStyle. copy };

// If the system is iOS7.0;

CGSize labelSize;

If (! [Text respondsToSelector: @ selector (boundingRectWithSize: options: attributes: context :)]) {

LabelSize = [text sizeWithFont: [UIFont systemFontOfSize: fontSize] constrainedToSize: maxSize lineBreakMode: NSLineBreakByWordWrapping];

}

// For IOS6.0

Else

{

LabelSize = [text boundingRectWithSize: maxSize

Options: NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading | NSStringDrawingTruncatesLastVisibleLine

Attributes: attributes

Context: nil]. size;

}

LabelSize. height = ceil (labelSize. height );

LabelSize. width = ceil (labelSize. width );

Return labelSize;

}

 

// Called Function

CGSize maxSize = CGSizeMake (MAXFLOAT, 40 );

CGSize titleSize = [self labelAutoCalculateRectWith: _ publicDetail. name FontSize: 15.0f MaxSize: maxSize];

UILabel * label = [UILabel alloc] init];

Label. frame = CGRectMake (0, 0, titleSize. width, titleSize. height );

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.