您的位置:首页 > 移动开发 > IOS开发

ios 中内容label高度自适应

2014-12-23 17:24 337 查看
首先并且最重要的是计算文本高度,然后再设置label的高度,

计算文本高度:

假设文本:

 NSString*strtest =@"
新华网北京12月16日电据新华社“新华国际”客户端报道,“一日之计在于晨”。克强总理15日的紧张日程从一顿早饭开始。天刚蒙蒙亮,哈萨克斯坦总理马西莫夫就来到克强总理下榻的酒店——北京大厦,邀请克强总理一起吃早餐。这是一顿简单的早餐,只有一张圆桌,两把椅子,一些简单的中西餐点。这也是一顿丰盛的早餐,两位总理在餐桌上就中哈产能合作达成的共识内容丰富,覆盖广泛。这更是一顿登高望远的早餐,这项合作不仅将惠及中哈两国人民,更将为区域内各国带来长远的共同利益。站在大厦23层的旋转餐厅,阿斯塔纳城尽收眼底,这里适合登高远眺。";
事实上ios 有两种方法:
ios7.0之前用:

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

之后用下面的方法比较好:

    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的宽度设置成计算时设置的宽度一致
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  label 高度自适应 iOS