Ios_ dynamically determine label width based on word count
IOS7 replaces obsolete iOS6-(cgsize) Sizewithfont with the following method: (Uifont *) Font method
-(Cgsize) Sizewithattributes: (Nsdictionary *) attrs;
// iOS7_API_根据文字 字数动态确定Label宽高// 设置Label的字体 HelveticaNeue CourierUIFont *fnt = [UIFont fontWithName:@"HelveticaNeue"size:24.0f];_nameLabel.font = fnt;// 根据字体得到NSString的尺寸CGSize size = [_nameLabel.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:fnt,NSFontAttributeName, nil]];// 名字的HCGFloat nameH = size.height;// 名字的WCGFloat nameW = size.width;_nameLabel.frame = CGRectMake(0, 0, nameW,nameH);
IOS7 uses the following method BoundingRectWithSize:options:attributes:context: Instead of sizewithfont:constrainedtosize in obsolete iOS6: Linebreakmode: Method
-
// 根据正文内容多少,动态确定正文content的frame
// 宽度W CGFloat contentW = self.bounds.size.width - _content.frame.origin.x - kMargin; // label的字体 HelveticaNeue Courier UIFont *fnt = [UIFont fontWithName:@ "HelveticaNeue" size: 18 .0f]; _content.font = fnt; _content.numberOfLines = 0 ; _content.lineBreakMode = NSLineBreakByWordWrapping; // iOS7中用以下方法替代过时的iOS6中的sizeWithFont:constrainedToSize:lineBreakMode:方法 CGRect tmpRect = [_content.text boundingRectWithSize:CGSizeMake(contentW, 1000 ) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:fnt,NSFontAttributeName, nil] context:nil]; // 高度H CGFloat contentH = tmpRect.size.height; NSLog(@ "调整后的显示宽度:%f,显示高度:%f" contentW,contentH); _content.frame = CGRectMake( 0 , 0 , contentW,contentH);
Ios_ dynamically determine label width based on word count