UILabel的自適應
UILabel的自動換行
UILabel * examp_LB = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, self.view.frame.size.width, 150)];
examp_LB.backgroundColor = [UIColor colorWithRed:1 green:1 blue:0 alpha:0.3f]; // 偏“黃色”
examp_LB.text = @"abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz";
// 自動換行
examp_LB.numberOfLines = 0; //必須設置為0行用踩,才會自動換行
examp_LB.lineBreakMode = NSLineBreakByCharWrapping; //結(jié)尾時锡垄,按“字符”換行
[self.view addSubview:examp_LB];
// NSParagraphStyle
typedef NS_ENUM(NSInteger, NSLineBreakMode) {
NSLineBreakByWordWrapping = 0, // Wrap at word boundaries, default
NSLineBreakByCharWrapping, // Wrap at character boundaries
NSLineBreakByClipping, // Simply clip
NSLineBreakByTruncatingHead, // Truncate at head of line: "...wxyz"
NSLineBreakByTruncatingTail, // Truncate at tail of line: "abcd..."
NSLineBreakByTruncatingMiddle // Truncate middle of line: "ab...yz"
} NS_ENUM_AVAILABLE(10_0, 6_0);
UILabel * examp_LB = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, self.view.frame.size.width, 50)];
效果:裝不下 (裝不完)
UILabel * examp_LB = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, self.view.frame.size.width, 100)];
效果:裝下,剩一點點空間
UILabel * examp_LB = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, self.view.frame.size.width, 150)];
效果:裝下妆丘,多出了很多空間
缺點:自己必須 保證UILabel所設置的高度完全 高于 所承載 字體的高度。否則會 裝不下勺拣!
UILabel的寬度自適應
使用寬度自適應時奶赠,(為了美觀????)一般都會設置字符串 居中:設置“textAlignment”為“NSTextAlignmentCenter”
示例:
UILabel * examp_LB2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 200, self.view.frame.size.width, 50)];
examp_LB2.backgroundColor = [UIColor colorWithRed:1 green:0 blue:1 alpha:0.2f];
examp_LB2.text = @"abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz";
examp_LB2.adjustsFontSizeToFitWidth = YES; //自適應 寬度
[self.view addSubview:examp_LB2];
效果:字符串 會全部 顯示在里面
“更改了字符串 長度,是其長度 減小后”的效果:
examp_LB2.text = @"abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcde";
效果:字符串長度 減短后
examp_LB2.text = @"abcdefghijk";
效果:字符串長度非常短時药有,不能完全填滿Label的長度
對 UILabel的寬度 進行更改
UILabel * examp_LB3 = [[UILabel alloc] initWithFrame:CGRectMake(0, 260, 150, 50)];
examp_LB3.backgroundColor = [UIColor colorWithRed:1 green:0 blue:1 alpha:0.2f];
examp_LB3.text = @"abcdefghijk";
examp_LB3.textAlignment = NSTextAlignmentCenter; //字跡 居中
examp_LB3.adjustsFontSizeToFitWidth = YES; //自適應 寬度
[self.view addSubview:examp_LB3];
效果:裝完
UILabel * examp_LB3 = [[UILabel alloc] initWithFrame:CGRectMake(0, 260, 100, 50)];
效果:有些許的空白
UILabel * examp_LB3 = [[UILabel alloc] initWithFrame:CGRectMake(0, 260, 150, 50)];
效果:有許多的空白
UILabel換行毅戈、自適應寬度
UILabel * examp_LB4 = [[UILabel alloc] initWithFrame:CGRectMake(0, 320, self.view.frame.size.width, 50)];
examp_LB4.backgroundColor = [UIColor colorWithRed:1 green:0 blue:1 alpha:0.2f];
examp_LB4.text = @"abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz";
examp_LB4.numberOfLines = 0; //行數(shù)設置為0
examp_LB4.adjustsFontSizeToFitWidth = YES; //自適應 寬度
[self.view addSubview:examp_LB4];
??:不能設置其 換行模式的屬性!!!!! 否則“adjustsFontSizeToFitWidth”的設置 將變?yōu)?strong>無效!
UILabel * examp_LB5 = [[UILabel alloc] initWithFrame:CGRectMake(0, 380, self.view.frame.size.width, 50)];
examp_LB5.backgroundColor = [UIColor colorWithRed:1 green:0 blue:1 alpha:0.2f];
examp_LB5.text = @"abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz";
examp_LB5.numberOfLines = 0;
examp_LB5.lineBreakMode = NSLineBreakByCharWrapping; //(??????)
// 由于設置了換行模式塑猖,自適應寬度變?yōu)闊o效
examp_LB5.adjustsFontSizeToFitWidth = YES; //自適應 寬度
[self.view addSubview:examp_LB5];
效果:
UILabel的 ??完全自適應??
要使用到 如下方法:
- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(nullable NSDictionary<NSString *, id> *)attributes context:(nullable NSStringDrawingContext *)context NS_AVAILABLE(10_11, 7_0);
來記錄下UILabel的frame,再讀取出來(返回類型: CGRect) 使用 其frame羊苟!
在使用的類里 對方法改寫后,如下:
// 傳入 文字感憾、字體和最大尺寸蜡励,即可得到寬、高
- (CGSize)sizeWithText:(NSString *)text andFont:(UIFont *)font maxSize:(CGSize)maxSize
{
NSDictionary *attrs = @{NSFontAttributeName : font};
return [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}
// 傳入文字阻桅、字體和最大寬度凉倚,即可得到寬、高
-(CGSize)sizeWithText:(NSString *)text font:(UIFont *)font maxW:(CGFloat)maxW
{
NSMutableDictionary *attrs=[NSMutableDictionary dictionary];
attrs[NSFontAttributeName]=font;
CGSize maxSize=CGSizeMake(maxW, MAXFLOAT);
return [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}
// 傳入文字嫂沉、字體 (默認:最大寬度)
- (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font
{
return [self sizeWithText:text font:font maxW:MAXFLOAT];
}
UILabel * examp_LB6 = [[UILabel alloc] initWithFrame:CGRectMake(0, 50, self.view.frame.size.width, 50)];
examp_LB6.backgroundColor = [UIColor colorWithRed:1 green:0 blue:1 alpha:0.2f];
// 自動換行
examp_LB6.numberOfLines = 0;
examp_LB6.lineBreakMode = NSLineBreakByCharWrapping;
[self.view addSubview:examp_LB6];
// 設置自適應 所需字串
NSString * str = @"abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz";
examp_LB6.text = str;
// 設置自適應 所需字體
UIFont *font = [UIFont fontWithName:@"Arial" size:12];
examp_LB6.font = font;
如下是三種方法的調(diào)用:
-
1.傳入 文字稽寒、字體和最大尺寸,即可得到寬趟章、高
// 傳入 文字杏糙、字體和最大尺寸慎王,即可得到寬、高 CGSize labelsize = [self sizeWithText:str andFont:font maxSize:CGSizeMake(self.view.frame.size.width, 100)]; examp_LB6.frame = CGRectMake(examp_LB6.frame.origin.x,examp_LB6.frame.origin.y, labelsize.width, labelsize.height);
效果:
-
2.傳入文字赖淤、字體和最大寬度,即可得到寬谅河、高
// 傳入文字咱旱、字體和最大寬度,即可得到寬绷耍、高 CGSize labelsize = [self sizeWithText:str font:font maxW:290]; //限定寬度 examp_LB6.frame = CGRectMake(examp_LB6.frame.origin.x,examp_LB6.frame.origin.y, labelsize.width, labelsize.height);
效果:
-
3.傳入文字、字體 (默認:最大寬度)
// 傳入文字褂始、字體 (默認:最大寬度) CGSize labelsize = [self sizeWithText:str font:font]; examp_LB6.frame = CGRectMake(examp_LB6.frame.origin.x,examp_LB6.frame.origin.y, labelsize.width, labelsize.height);
效果:會得到Label的最大長度
顯示出來是 屏幕的寬度。打上斷點 病袄,查看Label的最大長度:
當然 使用系統(tǒng)的“視圖位置關系”查看方法“Debug View Hierarchy” 枉然搂赋,是不能看到屏幕外的視圖。
使用一款叫“Reveal”的軟件脑奠,可以查看 屏幕外的視圖:
Reveal 下載地址:https://revealapp.com/download/
當然 我用的是 破解版~ ??????????????
Reveal-----視圖大小幅慌、位置關系 查看及調(diào)試宋欺。Reveal使用說明的文章 網(wǎng)上有很多,就不詳述了~
當然也可以直接 使用
- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(nullable NSDictionary<NSString *, id> *)attributes context:(nullable NSStringDrawingContext *)context NS_AVAILABLE(10_11, 7_0);
方法 所返回的“CGRect”結(jié)構(gòu)體胰伍。
NSDictionary *attribute_Dict = @{NSFontAttributeName: font};// 字體的字典
CGRect label_Rect = [str boundingRectWithSize:CGSizeMake(self.view.frame.size.width, 0) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading | NSStringDrawingTruncatesLastVisibleLine attributes:attribute_Dict context:nil];
float label_height = label_Rect.size.height;
float label_width = label_Rect.size.width;
examp_LB6.frame = CGRectMake(examp_LB6.frame.origin.x,examp_LB6.frame.origin.y, label_width, label_height);
當設置字符串居中 時:
examp_LB6.textAlignment = NSTextAlignmentCenter; //字跡 居中
效果:
下面是更改字符串的長度 示例齿诞,你就會清楚 UILabel的高、寬 完全自適應B钭狻5昏尽!I但汞!
NSString * str = @"abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcde";
效果:
// 長度 足夠短時 (寬度自適應)
NSString * str = @"abcdefghi";
效果:UILabel的高、寬 自適應
UILabel使用 富文本
Text Kit能夠很簡單實現(xiàn)一些復雜的文本 樣式以及布局私蕾,而Text Kit富文本框架用到的核心數(shù)據(jù)結(jié)構(gòu)就是屬性化字符串NSAttributeString
Text Kit指的是UIKit框架中用于提供高質(zhì)量排版服務的一些類和協(xié)議,它讓程序能夠存儲胡桃,排版和顯示文本信息踩叭,并支持排版所需要的所有特性(包括字距調(diào)整、連寫、換行和對齊等) 容贝。
- (instancetype)initWithString:(NSString *)str;
- (instancetype)initWithString:(NSString *)str attributes:(nullable NSDictionary<NSString *, id> *)attrs;
- (instancetype)initWithAttributedString:(NSAttributedString *)attrStr;
//使用NSAttributedString初始化自脯,跟NSMutableString,NSString類似
NSMutableAttributedString的屬性設置:
//為某一范圍內(nèi)文字設置多個屬性
- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;
//為某一范圍內(nèi)文字添加某個屬性
- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;
//為某一范圍內(nèi)文字添加多個屬性
- (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range;
//移除某范圍內(nèi)的某個屬性
- (void)removeAttribute:(NSString *)name range:(NSRange)range;
NSFontAttributeName 字體屬性(字體嗤疯、大小)冤今。 默認值:字體:Helvetica(Neue) 字號:12
NSForegroundColorAttributeNam 字體顏色,取值為 UIColor對象茂缚。 默認值為黑色
NSBackgroundColorAttributeName 字體所在區(qū)域背景顏色戏罢,取值為 UIColor對象。 默認值為nil, 透明色
NSLigatureAttributeName 連體屬性脚囊,取值為NSNumber 對象(整數(shù)),0 表示沒有連體字符悔耘,1 表示使用默認的連體字符
NSKernAttributeName 設定字符間距讲岁,取值為 NSNumber 對象(整數(shù)),正值間距加寬衬以,負值間距變窄
NSStrikethroughStyleAttributeName 刪除線缓艳,取值為 NSNumber 對象(整數(shù))
NSStrikethroughColorAttributeName 刪除線顏色,取值為 UIColor 對象看峻。 默認值為黑色
NSUnderlineStyleAttributeName 下劃線阶淘,取值為 NSNumber 對象(整數(shù)),枚舉常量 NSUnderlineStyle中的值互妓,與刪除線類似
NSUnderlineColorAttributeName 下劃線顏色溪窒,取值為 UIColor 對象。 默認值為黑色
NSStrokeWidthAttributeName 設置筆畫寬度冯勉,取值為 NSNumber 對象(整數(shù))澈蚌,負值填充效果,正值中空效果
NSStrokeColorAttributeName 填充部分顏色灼狰,不是字體顏色宛瞄,取值為 UIColor 對象
NSShadowAttributeName 設置陰影屬性,取值為 NSShadow 對象
NSTextEffectAttributeName 設置文本特殊效果交胚,取值為 NSString 對象坛悉,目前只有圖版印刷效果可用
NSBaselineOffsetAttributeName 設置基線偏移值,取值為 NSNumber (float),正值上偏承绸,負值下偏
NSObliquenessAttributeName 設置字形傾斜度,取值為 NSNumber (float),正值右傾挣轨,負值左傾
NSExpansionAttributeName 設置文本橫向拉伸屬性军熏,取值為 NSNumber (float),正值橫向拉伸文本,負值橫向壓縮文本
NSWritingDirectionAttributeName 設置文字書寫方向卷扮,從左向右書寫或者從右向左書寫
NSVerticalGlyphFormAttributeName 設置文字排版方向荡澎,取值為 NSNumber 對象(整數(shù))均践,0 表示橫排文本,1 表示豎排文本
NSAttachmentAttributeName 設置文本附件,取值為NSTextAttachment對象,常用于文字圖片混排
NSParagraphStyleAttributeName 設置文本段落排版格式摩幔,取值為 NSParagraphStyle 對象
NSLinkAttributeName 設置鏈接屬性彤委,點擊后調(diào)用瀏覽器打開指定URL地址
為富文本添加鏈接:iOS開發(fā)——超鏈接富文本
富文本的 各種屬性的展示 示例 網(wǎng)址:http://www.itnose.net/detail/6177538.html
舉個??:
// 垃圾代碼部分
UILabel * examp_Attrb_LB1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 50, self.view.frame.size.width, 50)];
examp_Attrb_LB1.backgroundColor = [UIColor colorWithRed:0.5 green:1 blue:0 alpha:0.2f];
[self.view addSubview:examp_Attrb_LB1];
UILabel * examp_Attrb_LB2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 110, self.view.frame.size.width, 50)];
examp_Attrb_LB2.backgroundColor = [UIColor colorWithRed:0.5 green:1 blue:0 alpha:0.2f];
[self.view addSubview:examp_Attrb_LB2];
UILabel * examp_Attrb_LB3 = [[UILabel alloc] initWithFrame:CGRectMake(0, 170, self.view.frame.size.width, 50)];
examp_Attrb_LB3.backgroundColor = [UIColor colorWithRed:0.5 green:1 blue:0 alpha:0.2f];
[self.view addSubview:examp_Attrb_LB3];
UILabel * examp_Attrb_LB4 = [[UILabel alloc] initWithFrame:CGRectMake(0, 260, self.view.frame.size.width, 50)];
examp_Attrb_LB4.backgroundColor = [UIColor colorWithRed:0.5 green:1 blue:0 alpha:0.2f];
[self.view addSubview:examp_Attrb_LB4];
UILabel * examp_Attrb_LB5 = [[UILabel alloc] initWithFrame:CGRectMake(0, 320, self.view.frame.size.width, 50)];
examp_Attrb_LB5.backgroundColor = [UIColor colorWithRed:0.5 green:1 blue:0 alpha:0.2f];
[self.view addSubview:examp_Attrb_LB5];
UILabel * examp_Attrb_LB6 = [[UILabel alloc] initWithFrame:CGRectMake(0, 380, self.view.frame.size.width, 150)];
examp_Attrb_LB6.backgroundColor = [UIColor colorWithRed:0.5 green:1 blue:0 alpha:0.2f];
[self.view addSubview:examp_Attrb_LB6];
//《《《《《《《《《《《《《 進入主題 》》》》》》》》》》》》》
// 富文本 字符串1
NSAttributedString * attrStr1 = [[NSAttributedString alloc] initWithString:@"abcdefghij"]; // 幾近無用??
// 不可變 富文本2 (附帶設置 富文本屬性(??全體??的屬性) )
NSAttributedString * attrStr2 = [[NSAttributedString alloc] initWithString:@"hijklmnopqr" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:30.f],NSForegroundColorAttributeName:RGB(137, 198, 41)}];
// 不可變 富文本3 (??復制??一份富文本 )
NSAttributedString * attrStr3 = [[NSAttributedString alloc] initWithAttributedString:attrStr2]; // ??復制??一份富文本
//=======================================================
// 可變 富文本4
NSMutableAttributedString * attrStr4 = [[NSMutableAttributedString alloc] initWithAttributedString:attrStr2];
// 獲取“mno”字符串 ??所在范圍??
NSRange rag_1 = [attrStr4.string localizedStandardRangeOfString:@"mno"];
// 添加 “mno”字符串所在范圍 字體 屬性
[attrStr4 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:10.f] range:rag_1];
//=======================================================
// 可變 富文本5
NSMutableAttributedString * attrStr5 = [[NSMutableAttributedString alloc] initWithString:@"stuvwxyz"];
// 要添加或更改屬性 的字典
NSDictionary * attr_Dict = @{NSForegroundColorAttributeName:[UIColor orangeColor],
NSUnderlineStyleAttributeName:[NSNumber numberWithFloat:1.0]
}; //字體顏色 及 下劃線
// ??添加?? 范圍內(nèi) 富文本屬性
[attrStr5 addAttributes:attr_Dict range:NSMakeRange(0, attrStr5.length)]; // 整個字符串(NSMakeRange(0, attrStr5.length))的范圍
// 要添加或更改屬性 的字典
NSDictionary * attr_Dict2 = @{NSBackgroundColorAttributeName:[UIColor cyanColor],
NSForegroundColorAttributeName:[UIColor blueColor],
NSStrikethroughStyleAttributeName:[NSNumber numberWithFloat:1.0]
}; //背景色、字體顏色 及 刪除線
// 要添加或更改屬性的 范圍
NSRange rag_2 = NSMakeRange(2, 2);
// ??設置?? 范圍內(nèi) 富文本屬性
[attrStr5 setAttributes:attr_Dict2 range:rag_2];
//=======================================================
// 可變 富文本6
NSMutableAttributedString * attrStr6 = [[NSMutableAttributedString alloc] initWithString:@"abcdefghijklmnopqrstuvwxyz"];
// 隨機色Label
for (int i = 0; i < attrStr6.string.length; i ++) {
// 所有更改屬性 的字典
NSDictionary * attr_Dict = @{NSForegroundColorAttributeName:[UIColor colorWithRed:arc4random()%256/255.f green:arc4random()%256/255.f blue:arc4random()%256/255.f alpha:1],
NSFontAttributeName:[UIFont systemFontOfSize:(arc4random()%20+30)/1.f]
}; // 字體:隨機顏色或衡、隨機大小
// 要添加或更改屬性的 范圍
NSRange rag = NSMakeRange(i, 1);
// ??設置?? 范圍內(nèi) 富文本屬性
[attrStr6 setAttributes:attr_Dict range:rag];
}
// Label添加 富文本字符串
examp_Attrb_LB1.attributedText = attrStr1;
examp_Attrb_LB2.attributedText = attrStr2;
examp_Attrb_LB3.attributedText = attrStr3;
examp_Attrb_LB4.attributedText = attrStr4;
examp_Attrb_LB5.attributedText = attrStr5;
examp_Attrb_LB6.attributedText = attrStr6;
效果:
加上 自動換行代碼后焦影,examp_Attrb_LB6實現(xiàn)換行:
// 自動換行
examp_Attrb_LB6.numberOfLines = 0;
examp_Attrb_LB6.lineBreakMode = NSLineBreakByCharWrapping;
效果:
富文本在UITextView、UITextField中的示例:
UITextView * tv = [[UITextView alloc] initWithFrame:CGRectMake(9, 20, 100, 200)];
tv.backgroundColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:0.2f];
tv.attributedText = attrStr6;
[self.view addSubview:tv];
UITextField * tf = [[UITextField alloc] initWithFrame:CGRectMake(10, 260, 200, 20)];
tf.backgroundColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:0.2f];
tf.attributedText = attrStr6;
[self.view addSubview:tf];
效果:
在字符串后面添加 字符串時斯辰,后面的富文本 會復制 上一個富文本字符的字體、顏色和大小坡疼。
更多方法和屬性說明 詳見蘋果官方說明文檔:https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSMutableAttributedString_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40003689
一般富文本也就簡單的顯示在 一彬呻、兩處 地方,在定制控件時 封裝好就可以了柄瑰。
當然你自己可以給UILabel 加個使用富文本的類別~