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)

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

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