你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> ios 中內容label高度自適應

ios 中內容label高度自適應

編輯:IOS開發綜合

首先並且最重要的是計算文本高度,然後再設置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的寬度設置成計算時設置的寬度一致

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved