根据文字计算出label的高度

ios7.0之前用:

[strtestsizeWithFont:ContentFontconstrainedToSize:CGSizeMake(ScreenWeight -20, 1000) lineBreakMode:NSLineBreakByWordWrapping];

 

ios7之后

CGRect frame = [strtestboundingRectWithSize:CGSizeMake(220,1000) options:NSStringDrawingUsesLineFragmentOriginattributes:@{NSFontAttributeName:[UIFontsystemFontOfSize:10]}context:nil];

attributes参数有:

 NSFontAttributeName // UIFont, default Helvetica(Neue) 12

NSParagraphStyleAttributeName // NSParagraphStyle, default defaultParagraphStyle

NSForegroundColorAttributeName // UIColor, default blackColor

NSBackgroundColorAttributeName // UIColor, default nil: no background

NSLigatureAttributeName // NSNumber containing integer, default 1: default ligatures, 0: no ligatures

NSKernAttributeName // NSNumber containing floating point value, in points; amount to modify default kerning. 0 means kerning is disabled.

NSStrikethroughStyleAttributeName ; // NSNumber containing integer, default 0: no strikethrough

NSUnderlineStyleAttributeName // NSNumber containing integer, default 0: no underline

NSStrokeColorAttributeName // UIColor, default nil: same as foreground color

NSStrokeWidthAttributeName // NSNumber containing floating point value, in percent of font point size, default 0: no stroke; positive for stroke alone, negative for stroke and fill (a typical value for outlined text would be 3.0)

NSShadowAttributeName ; // NSShadow, default nil: no shadow

NSTextEffectAttributeName // NSString, default nil: no text effect

 

NSAttachmentAttributeName // NSTextAttachment, default nil

NSLinkAttributeName // NSURL (preferred) or NSString

NSBaselineOffsetAttributeName // NSNumber containing floating point value, in points; offset from baseline, default 0

NSUnderlineColorAttributeName // UIColor, default nil: same as foreground color

NSStrikethroughColorAttributeName // UIColor, default nil: same as foreground color

NSObliquenessAttributeName // NSNumber containing floating point value; skew to be applied to glyphs, default 0: no skew

NSExpansionAttributeName // NSNumber containing floating point value; log of expansion factor to be applied to glyphs, default 0: no expansion

建立label的时候注意:

① label的font,必须和计算时用的font一样

② label的numberOfLines要设置为零

③ label的宽度设置成计算时设置的宽度一致

 

注意:在UITextView中用这个计算,得到的高度偏小,主要是UITextView中又默认的边距,需要自己根据具体情况进行相应的调整,特别是在文字比较多的情况下

 

 

原文地址:https://www.cnblogs.com/Ohero/p/4395832.html