UILable

UILableUIKit下的控件,繼承UIView,是iOS開發常用的控件。

項目中一般的用法:

    CGRect rect=CGRectMake(20, 100, 350, 40); //(x,y,width,height)
    UILabel *label=[[UILabel alloc] initWithFrame:rect];//創建控件,并設置相對父視圖右上角的位置
    label.backgroundColor=[UIColor lightGrayColor];//標簽的背景顏色
    label.textAlignment=NSTextAlignmentCenter;//標簽文字的對齊方式
    label.textColor=[UIColor blackColor];//標簽文字的顏色
    label.font=[UIFont systemFontOfSize:18.0];//標簽文字的字體大小
    label.text=@"這里是設置標簽顯示的內容,為字符串";//標簽文字顯示的內容
    [self.view addSubview:label];//將標簽添加到父視圖中
屏幕快照 2017-11-02 16.58.49.png

多行顯示

如果標簽內容很長,需要全部顯示,這個時候,我們需要多行顯示

 label.text=@"這里是設置標簽顯示的內容,為字符串,勝利大街方式肯定九分褲水電費健身卡的房價上島咖啡牲口的尖峰時刻的房價是快遞費健身卡老地方殺戮空間都煩死了快遞費技術領導開發計算樓房";//標簽文字顯示的內容

我們需要這么設置

CGRect rect=CGRectMake(20, 100, 350,120); //(x,y,width,height) 調整標簽高度
label.numberOfLines=0;//根據內容顯示多行,因為行數不是固定,需要設置為0
label.lineBreakMode=NSLineBreakByCharWrapping;//需要設置換行轉折的方式
屏幕快照 2017-11-02 17.18.25.png

多行顯示成功了!換行方式這個,大家要留意一下,是有這幾種方式

//換行方式
typedef NS_ENUM(NSInteger, NSLineBreakMode) {
    NSLineBreakByWordWrapping = 0,      // 以單詞為單位換行, 默認方式
    NSLineBreakByCharWrapping,      // 以字符為單位換行(換行時單詞可能被分割)
    NSLineBreakByClipping,      // Simply clip
    NSLineBreakByTruncatingHead,    // 多行顯示不完整時會以: "...wxyz"最后一行開頭省略號,省略中間部分
    NSLineBreakByTruncatingTail,    // 多行顯示不完整時會以: "abc..."最后一行末尾省略號,省略剩余部分
    NSLineBreakByTruncatingMiddle   // 多行顯示不完整時會以: "ab..yz."最后一行中間省略號,省略中間部分
} NS_ENUM_AVAILABLE(10_0, 6_0);

動態計算標簽的高度或寬度

在實際項目中,會遇到標簽顯示內容是接口獲取,這個時候要想將標簽內容顯示完整,就需要動態計算標簽所需的高度或寬度

固定寬度,動態獲取高度
//iOS 7之前的方法
CGSize titleSize = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(350, MAXFLOAT)]; 
label.frame=CGRectMake(20, 100, 350,titleSize.height);
//iOS 7之后的方法
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
 [style setLineBreakMode:NSLineBreakByCharWrapping];
 [style setAlignment:NSTextAlignmentLeft];
 NSDictionary *dic = @{NSFontAttributeName: label.font,NSParagraphStyleAttributeName: style};
 CGSize titleSize = [label.text boundingRectWithSize:CGSizeMake(350, MAXFLOAT) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:dic context:nil].size;
 label.frame=CGRectMake(20, 100, 350,titleSize.height);
固定高度,動態獲取寬度
//iOS 7之前的方法
CGSize titleSize = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(MAXFLOAT, 40)]; 
label.frame=CGRectMake(20, 100,titleSize.width ,40); 
//iOS 7之后的方法
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
 [style setLineBreakMode:NSLineBreakByCharWrapping];
 [style setAlignment:NSTextAlignmentLeft];
 NSDictionary *dic = @{NSFontAttributeName: label.font,NSParagraphStyleAttributeName: style};
 CGSize titleSize = [label.text boundingRectWithSize:CGSizeMake(MAXFLOAT, 40) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:dic context:nil].size;
label.frame=CGRectMake(20, 100,titleSize.width ,40);     

標簽字體間距、行間距的設置

項目中,有時為了UI布局的美觀,需要調整字間距、行間距

    CGRect rect=CGRectMake(20, 100, 350,100); //(x,y,width,height)
    UILabel *label=[[UILabel alloc] initWithFrame:rect];//創建控件,并設置相對父視圖右上角的位置
    label.backgroundColor=[UIColor lightGrayColor];//標簽的背景顏色
    label.textAlignment=NSTextAlignmentLeft;//標簽文字的對齊方式
    label.textColor=[UIColor blackColor];//標簽文字的顏色
    label.font=[UIFont systemFontOfSize:18.0];//標簽文字的字體大小
    label.text=@"這里是設置標簽顯示的內容,為字符串,勝利大街方式肯定九分褲水電費健身卡的房價上島咖啡牲口的尖峰時刻的房價是快遞費健身卡老地方殺戮空間都煩死了快遞費技術領導開發計算樓房";//標簽文字顯示的內容
    [self.view addSubview:label];//將標簽添加到父視圖中
    
    label.numberOfLines=0;
    label.lineBreakMode=NSLineBreakByTruncatingTail;

    
    NSDictionary *dic = @{NSKernAttributeName:@10.f
                          };//字間距
    NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:label.text attributes:dic];
    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:30];//行間距
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [label.text length])];
    [label setAttributedText:attributedString];
    [label sizeToFit];//lable自動適配
屏幕快照 2017-11-03 10.21.34.png

上面一段代碼,也能看到UILable的另一種高度的適配方法 [label sizeToFit] (注:可以設置高度固定,適配寬度嗎?)

標簽中部分字體屬性設置

某個范圍字體變色,例如“勝利大街”

  //要變色的范圍
 NSRange blueRange=NSMakeRange([label.text rangeOfString:@"勝利大街"].location, [label.text rangeOfString:@"勝利大街"].length);
//設置變色(藍色)
 [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:blueRange];

直接在上面設置間距的代碼中插入這段代碼,可以得到下圖效果:


屏幕快照 2017-11-03 10.45.18.png

可能你注意到了,間距、標簽字體不同顏色設置用到了NSParagraphStyleAttributeNameNSForegroundColorAttributeName這兩個關鍵詞,類似鍵值NSAttributedString中還有

// 屬性文本的鍵值
NSFontAttributeName                設置字體屬性,默認值:字體:Helvetica(Neue) 字號:12
NSForegroundColorAttributeName     設置字體顏色,取值為 UIColor對象,默認值為黑色
NSBackgroundColorAttributeName     設置字體所在區域背景顏色,取值為 UIColor對象,默認值為nil, 透明色
NSLigatureAttributeName            設置連體屬性,取值為NSNumber 對象(整數),0 表示沒有連體字符,1 表示使用默認的連體字符
NSKernAttributeName                設定字符間距,取值為 NSNumber 對象(整數),正值間距加寬,負值間距變窄
NSStrikethroughStyleAttributeName  設置刪除線,取值為 NSNumber 對象(整數)
NSStrikethroughColorAttributeName  設置刪除線顏色,取值為 UIColor 對象,默認值為黑色
NSUnderlineStyleAttributeName      設置下劃線,取值為 NSNumber 對象(整數),枚舉常量 NSUnderlineStyle中的值,與刪除線類似
NSUnderlineColorAttributeName      設置下劃線顏色,取值為 UIColor 對象,默認值為黑色
NSStrokeWidthAttributeName         設置筆畫寬度,取值為 NSNumber 對象(整數),負值填充效果,正值中空效果
NSStrokeColorAttributeName         填充部分顏色,不是字體顏色,取值為 UIColor 對象
NSShadowAttributeName              設置陰影屬性,取值為 NSShadow 對象
NSTextEffectAttributeName          設置文本特殊效果,取值為 NSString 對象,目前只有圖版印刷效果可用:
NSBaselineOffsetAttributeName      設置基線偏移值,取值為 NSNumber (float),正值上偏,負值下偏
NSObliquenessAttributeName         設置字形傾斜度,取值為 NSNumber (float),正值右傾,負值左傾
NSExpansionAttributeName           設置文本橫向拉伸屬性,取值為 NSNumber (float),正值橫向拉伸文本,負值橫向壓縮文本
NSWritingDirectionAttributeName    設置文字書寫方向,從左向右書寫或者從右向左書寫
NSVerticalGlyphFormAttributeName   設置文字排版方向,取值為 NSNumber 對象(整數),0 表示橫排文本,1 表示豎排文本
NSLinkAttributeName                設置鏈接屬性,點擊后調用瀏覽器打開指定URL地址
NSAttachmentAttributeName          設置文本附件,取值為NSTextAttachment對象,常用于文字圖片混排
NSParagraphStyleAttributeName      設置文本段落排版格式,取值為 NSParagraphStyle 對象 

UILable控件類的屬性


@class UIColor, UIFont;

NS_CLASS_AVAILABLE_IOS(2_0) @interface UILabel : UIView <NSCoding, UIContentSizeCategoryAdjusting>
//NSCoding表示支持解歸檔
//該UIContentSizeCategoryAdjusting協議提供了adjustsFontForContentSizeCategory可用于確定在設備UIContentSizeCategory更改時采用元素是否應更新其字體的屬性。

//UILable顯示內容
@property(nullable, nonatomic,copy)   NSString           *text;            // default is nil
//字體
@property(null_resettable, nonatomic,strong) UIFont      *font;            // default is nil (system font 17 plain)
//字體顏色
@property(null_resettable, nonatomic,strong) UIColor     *textColor;       // default is nil (text draws black)
//陰影顏色
@property(nullable, nonatomic,strong) UIColor            *shadowColor;     // default is nil (no shadow)
//陰影偏移量
@property(nonatomic)        CGSize             shadowOffset;    // default is CGSizeMake(0, -1) -- a top shadow
//字體對齊方式
@property(nonatomic)        NSTextAlignment    textAlignment;   // default is NSTextAlignmentNatural (before iOS 9, the default was NSTextAlignmentLeft)
//多行文字換行方式
@property(nonatomic)        NSLineBreakMode    lineBreakMode;   // default is NSLineBreakByTruncatingTail. used for single and multiple lines of text

// the underlying attributed string drawn by the label, if set, the label ignores the properties above.
//文本屬性
@property(nullable, nonatomic,copy)   NSAttributedString *attributedText NS_AVAILABLE_IOS(6_0);  // default is nil

// the 'highlight' property is used by subclasses for such things as pressed states. it's useful to make it part of the base class as a user property
//高亮文字顏色(使用場景,例如cell點擊后,其上Labal的字體顏色變化,通過highlighted屬性控制)
@property(nullable, nonatomic,strong)               UIColor *highlightedTextColor; // default is nil
//是否高亮
@property(nonatomic,getter=isHighlighted) BOOL     highlighted;          // default is NO

//是否可交互
@property(nonatomic,getter=isUserInteractionEnabled) BOOL userInteractionEnabled;  // default is NO
//設置文字是否可變
@property(nonatomic,getter=isEnabled)                BOOL enabled;                 // default is YES. changes how the label is drawn

// this determines the number of lines to draw and what to do when sizeToFit is called. default value is 1 (single line). A value of 0 means no limit
// if the height of the text reaches the # of lines or the height of the view is less than the # of lines allowed, the text will be
// truncated using the line break mode.
//內容過多時,分幾行顯示,自適應時設置為0
@property(nonatomic) NSInteger numberOfLines;

// these next 3 properties allow the label to be autosized to fit a certain width by scaling the font size(s) by a scaling factor >= the minimum scaling factor
// and to specify how the text baseline moves when it needs to shrink the font.
//文字過多時,是否縮小文字以適應固定寬度
@property(nonatomic) BOOL adjustsFontSizeToFitWidth;         // default is NO
@property(nonatomic) UIBaselineAdjustment baselineAdjustment; // default is UIBaselineAdjustmentAlignBaselines
/**
UIBaselineAdjustmentAlignBaselines=0,默認,文本最上端與中線對齊。  
UIBaselineAdjustmentAlignCenters,   文本中線與label中線對齊。  
UIBaselineAdjustmentNone,  文本最低端與label中線對齊。
**/

//設置最小字體,與minimumFontSize相同,minimumFontSize在IOS 6后不能使用。
@property(nonatomic) CGFloat minimumScaleFactor NS_AVAILABLE_IOS(6_0); // default is 0.0


// Tightens inter-character spacing in attempt to fit lines wider than the available space if the line break mode is one of the truncation modes before starting to truncate.
// The maximum amount of tightening performed is determined by the system based on contexts such as font, line width, etc.
//收縮字符間距允許截斷
@property(nonatomic) BOOL allowsDefaultTighteningForTruncation NS_AVAILABLE_IOS(9_0); // default is NO

// override points. can adjust rect before calling super.
// label has default content mode of UIViewContentModeRedraw

//重寫UILabel布局
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines;
- (void)drawTextInRect:(CGRect)rect;


// Support for constraint-based layout (auto layout)
// If nonzero, this is used when determining -intrinsicContentSize for multiline labels
//這個屬性是用來設置多行label的最大寬度的
//當自動布局的時候約束這個label的時候這個屬性會起作用
//在自動布局添加約束中,若文本超過了指定的最大寬度的時候 文本會另起一行 從而增加了label的高度
@property(nonatomic) CGFloat preferredMaxLayoutWidth NS_AVAILABLE_IOS(6_0);


// deprecated:
//設置最小字體minimumFontSize在IOS 6后不能使用。
roperty(nonatomic) 
CGFloat minimumFontSize NS_DEPRECATED_IOS(2_0, 6_0) __TVOS_PROHIBITED; // deprecated - use minimumScaleFactor. default is 0.0

// Non-functional.  Hand tune by using NSKernAttributeName to affect tracking, or consider using the allowsDefaultTighteningForTruncation property.
@property(nonatomic) BOOL adjustsLetterSpacingToFitWidth NS_DEPRECATED_IOS(6_0,7_0) __TVOS_PROHIBITED;

@end


一些常用的第三方Lable控件

TTTAttributedLabel
TYAttributedLabel
SDAutoLayout
LTMorphingLabel(swift)

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,283評論 6 530
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 97,947評論 3 413
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,094評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,485評論 1 308
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,268評論 6 405
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,817評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,906評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,039評論 0 285
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,551評論 1 331
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,502評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,662評論 1 366
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,188評論 5 356
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 43,907評論 3 345
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,304評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,563評論 1 281
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,255評論 3 389
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,637評論 2 370

推薦閱讀更多精彩內容

  • 問答題47 /72 常見瀏覽器兼容性問題與解決方案? 參考答案 (1)瀏覽器兼容問題一:不同瀏覽器的標簽默認的外補...
    _Yfling閱讀 13,774評論 1 92
  • HTML標簽解釋大全 一、HTML標記 標簽:!DOCTYPE 說明:指定了 HTML 文檔遵循的文檔類型定義(D...
    米塔塔閱讀 3,283評論 1 41
  • ¥開啟¥ 【iAPP實現進入界面執行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個線程,因...
    小菜c閱讀 6,477評論 0 17
  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,142評論 4 61
  • 前言:UI控件整理之UILable 一、UILabel 效果圖基本代碼實現 UILabel *titleLa = ...
    心如止水的魚閱讀 171評論 0 0