您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 技巧大全

你真的了解 UIButton 與 UILabel 嗎?屬性與枚舉全解

編輯:iOS 技巧大全

UIButton 和 UILabel 是 iOS 裡出現頻率最高的兩個視圖,但很多人對它們的用法停留在「能顯示就行」。實際上,這兩個類暴露了大量細粒度屬性,理解透徹之後能省下不少自定義的力氣。

一、UIButton 的定義

@class UIImage, UIFont, UIColor, UIImageView, UILabel;

// UIButton 的樣式
typedef NS_ENUM(NSInteger, UIButtonType) {
    UIButtonTypeCustom = 0,           // 自定義,無任何系統樣式
    UIButtonTypeSystem NS_ENUM_AVAILABLE_IOS(7_0),  // 標準系統按鈕
    UIButtonTypeDetailDisclosure,     // 藍色披露按鈕,可放在任意文字旁
    UIButtonTypeInfoLight,            // 淺色小圓圈信息按鈕
    UIButtonTypeInfoDark,             // 深色圓圈信息按鈕,適用於白色背景
    UIButtonTypeContactAdd,           // 藍色加號按鈕
    UIButtonTypeRoundedRect = UIButtonTypeSystem  // 白色圓角矩形
};

@interface UIButton : UIControl <NSCoding>

+ (instancetype)buttonWithType:(UIButtonType)buttonType;

@property(nonatomic) UIEdgeInsets contentEdgeInsets;  // 默認 UIEdgeInsetsZero,內容四周邊緣
@property(nonatomic) UIEdgeInsets titleEdgeInsets;    // 默認 UIEdgeInsetsZero,文字四周邊緣
@property(nonatomic) BOOL reversesTitleShadowWhenHighlighted; // 默認 NO,高亮時是否反轉文字陰影
@property(nonatomic) UIEdgeInsets imageEdgeInsets;    // 默認 UIEdgeInsetsZero,圖標四周邊緣

@property(nonatomic) BOOL adjustsImageWhenHighlighted; // 默認 YES
@property(nonatomic) BOOL adjustsImageWhenDisabled;    // 默認 YES,禁用時圖像變淡
@property(nonatomic) BOOL showsTouchWhenHighlighted;   // 默認 NO,設為 YES 時按下會發光

@property(null_resettable, nonatomic, strong) UIColor *tintColor NS_AVAILABLE_IOS(5_0);

// 只讀:獲取當前 buttonType
@property(nonatomic, readonly) UIButtonType buttonType;

// 分狀態設置
- (void)setTitle:(nullable NSString *)title forState:(UIControlState)state;
- (void)setTitleColor:(nullable UIColor *)color forState:(UIControlState)state UI_APPEARANCE_SELECTOR;
- (void)setTitleShadowColor:(nullable UIColor *)color forState:(UIControlState)state UI_APPEARANCE_SELECTOR;
- (void)setImage:(nullable UIImage *)image forState:(UIControlState)state;
- (void)setBackgroundImage:(nullable UIImage *)image forState:(UIControlState)state UI_APPEARANCE_SELECTOR;
- (void)setAttributedTitle:(nullable NSAttributedString *)title forState:(UIControlState)state NS_AVAILABLE_IOS(6_0);

// 分狀態取值
- (nullable NSString *)titleForState:(UIControlState)state;
- (nullable UIColor *)titleColorForState:(UIControlState)state;
- (nullable UIColor *)titleShadowColorForState:(UIControlState)state;
- (nullable UIImage *)imageForState:(UIControlState)state;
- (nullable UIImage *)backgroundImageForState:(UIControlState)state;
- (nullable NSAttributedString *)attributedTitleForState:(UIControlState)state NS_AVAILABLE_IOS(6_0);

// 只讀:當前生效的值(取決於當前 state)
@property(nullable, nonatomic, readonly, strong) NSString *currentTitle;
@property(nonatomic, readonly, strong) UIColor *currentTitleColor;
@property(nullable, nonatomic, readonly, strong) UIColor *currentTitleShadowColor;
@property(nullable, nonatomic, readonly, strong) UIImage *currentImage;
@property(nullable, nonatomic, readonly, strong) UIImage *currentBackgroundImage;
@property(nullable, nonatomic, readonly, strong) NSAttributedString *currentAttributedTitle NS_AVAILABLE_IOS(6_0);

@property(nullable, nonatomic, readonly, strong) UILabel *titleLabel NS_AVAILABLE_IOS(3_0);
@property(nullable, nonatomic, readonly, strong) UIImageView *imageView NS_AVAILABLE_IOS(3_0);

// 各層邊界計算
- (CGRect)backgroundRectForBounds:(CGRect)bounds;
- (CGRect)contentRectForBounds:(CGRect)bounds;
- (CGRect)titleRectForContentRect:(CGRect)contentRect;
- (CGRect)imageRectForContentRect:(CGRect)contentRect;

@end

UIButton 繼承自 UIControl,並遵循 NSCoding 協議。

知識點 1:UIControlState 枚舉

enum {
    UIControlStateNormal       = 0,           // 常態
    UIControlStateHighlighted  = 1 << 0,     // 高亮(手指按下)
    UIControlStateDisabled     = 1 << 1,     // 禁用
    UIControlStateSelected     = 1 << 2,     // 選中
    UIControlStateApplication  = 0x00FF0000,  // 供應用自定義使用
    UIControlStateReserved     = 0xFF000000   // 供框架內部預留
};
typedef NSUInteger UIControlState;

注意這些值是位掩碼,可以組合。比如一個按鈕同時處於「高亮」和「選中」狀態時,其 state 就是 UIControlStateHighlighted | UIControlStateSelected。這也解釋了為什麼 setTitle:forState: 中使用 UIControlStateNormal 設置的值,會在其他所有狀態沒有專門配置時作為兜底呈現。

知識點 2:contentHorizontalAlignment

它可以設置按鈕文字的對齊方式。要注意這並不是 UIButton 自己的屬性,而是其父類 UIControl 提供的:

typedef NS_ENUM(NSInteger, UIControlContentHorizontalAlignment) {
    UIControlContentHorizontalAlignmentCenter = 0,  // 居中(默認)
    UIControlContentHorizontalAlignmentLeft   = 1,  // 左對齊
    UIControlContentHorizontalAlignmentRight  = 2,  // 右對齊
    UIControlContentHorizontalAlignmentFill   = 3   // 填充
};

同樣層級的還有 contentVerticalAlignment,用於控制垂直方向。

知識點 3:UIControlEvents 事件類型

typedef NS_OPTIONS(NSUInteger, UIControlEvents) {
    UIControlEventTouchDown           = 1 << 0,  // 單指按下
    UIControlEventTouchDownRepeat     = 1 << 1,  // 多指按下(第二、三、四根手指)
    UIControlEventTouchDragInside     = 1 << 2,  // 在控件範圍內拖動
    UIControlEventTouchDragOutside    = 1 << 3,  // 在控件範圍外拖動
    UIControlEventTouchDragEnter      = 1 << 4,  // 從外拖入範圍內
    UIControlEventTouchDragExit       = 1 << 5,  // 從範圍內拖出
    UIControlEventTouchUpInside       = 1 << 6,  // 在控件內部抬起(即「點擊」)
    UIControlEventTouchUpOutside      = 1 << 7,  // 在控件外部抬起
    UIControlEventTouchCancel         = 1 << 8,  // 觸摸被系統打斷(來電、鎖屏等)

    UIControlEventValueChanged        = 1 << 12, // 數值變化(slider、segmented control 等)

    UIControlEventEditingDidBegin     = 1 << 16, // 開始編輯
    UIControlEventEditingChanged      = 1 << 17, // 文本被修改
    UIControlEventEditingDidEnd       = 1 << 18, // 編輯結束
    UIControlEventEditingDidEndOnExit = 1 << 19, // 按回車結束編輯

    UIControlEventAllTouchEvents      = 0x00000FFF, // 所有觸摸事件
    UIControlEventAllEditingEvents    = 0x000F0000, // 所有編輯事件
    UIControlEventApplicationReserved = 0x0F000000, // 供應用使用
    UIControlEventSystemReserved      = 0xF0000000, // 供框架使用
    UIControlEventAllEvents           = 0xFFFFFFFF  // 所有事件
};

為什麼日常點擊都用 UIControlEventTouchUpInside 而不是 TouchDown?因為 TouchUpInside 要求手指必須在控件內部抬起才算有效點擊——用戶按下去又滑走,是不應該觸發動作的。這是系統預設的交互約定。

二、UILabel 的定義

@class UIColor, UIFont;

@interface UILabel : UIView <NSCoding>

@property(nullable, nonatomic, copy) NSString *text;              // 文本內容
@property(null_resettable, nonatomic, strong) UIFont *font;       // 字體,默認系統 17pt
@property(null_resettable, nonatomic, strong) UIColor *textColor; // 文本顏色
@property(nullable, nonatomic, strong) UIColor *shadowColor;      // 陰影顏色
@property(nonatomic) CGSize shadowOffset;                         // 默認 CGSizeMake(0, -1)
@property(nonatomic) NSTextAlignment textAlignment;               // 默認 NSTextAlignmentLeft
@property(nonatomic) NSLineBreakMode lineBreakMode;               // 默認 NSLineBreakByTruncatingTail

// 富文本
@property(nullable, nonatomic, copy) NSAttributedString *attributedText NS_AVAILABLE_IOS(6_0);

@property(nullable, nonatomic, strong) UIColor *highlightedTextColor; // 默認 nil
@property(nonatomic, getter=isHighlighted) BOOL highlighted;          // 默認 NO
@property(nonatomic, getter=isUserInteractionEnabled) BOOL userInteractionEnabled; // 默認 NO
@property(nonatomic, getter=isEnabled) BOOL enabled;                  // 默認 YES

@property(nonatomic) NSInteger numberOfLines;          // 0 表示不限制行數
@property(nonatomic) BOOL adjustsFontSizeToFitWidth;   // 默認 NO,是否按寬度自動縮字號
@property(nonatomic) UIBaselineAdjustment baselineAdjustment;
@property(nonatomic) CGFloat minimumScaleFactor NS_AVAILABLE_IOS(6_0);  // 默認 0.0
@property(nonatomic) BOOL allowsDefaultTighteningForTruncation NS_AVAILABLE_IOS(9_0);

// 用於重寫佈局
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines;
- (void)drawTextInRect:(CGRect)rect;

// 多行 label 的最大寬度,在自動佈局約束中生效:
// 文本超過該寬度時會換行,從而增加 label 高度
@property(nonatomic) CGFloat preferredMaxLayoutWidth NS_AVAILABLE_IOS(6_0);

// 以下兩個在 iOS 7 後已廢棄
@property(nonatomic) CGFloat minimumFontSize NS_DEPRECATED_IOS(2_0, 6_0);
@property(nonatomic) BOOL adjustsLetterSpacingToFitWidth NS_DEPRECATED_IOS(6_0, 7_0);

@end

UILabel 繼承自 UIView,同樣遵循 NSCoding。

知識點 1:NSLineBreakMode 枚舉

默認值是 NSLineBreakByTruncatingTail:

NSLineBreakByWordWrapping      按單詞換行,剩餘內容不顯示
NSLineBreakByCharWrapping      按字符換行,剩餘內容不顯示
NSLineBreakByClipping          能顯示多少顯示多少,多的直接截掉(可能只顯示半個字)
NSLineBreakByTruncatingHead    一行放不下時顯示為 ...abcd
NSLineBreakByTruncatingTail    一行放不下時顯示為 abcd...(默認)
NSLineBreakByTruncatingMiddle  一行放不下時顯示為 ab...cd

知識點 2:NSTextAlignment 枚舉

NSTextAlignmentLeft       = 0,  // 左對齊(默認)
NSTextAlignmentCenter     = 1,  // 居中
NSTextAlignmentRight      = 2,  // 右對齊
NSTextAlignmentJustified  = 3,  // 兩端對齊,段落最後一行按 natural 處理
NSTextAlignmentNatural    = 4   // 依腳本語言的默認對齊方式

知識點 3:NSAttributedString 支持的屬性

NSFontAttributeName              // 字體,value 為 UIFont
NSParagraphStyleAttributeName    // 段落風格(對齊、換行、行距等),value 為 NSParagraphStyle
NSForegroundColorAttributeName   // 文字顏色,value 為 UIColor
NSBackgroundColorAttributeName   // 背景色,value 為 UIColor
NSLigatureAttributeName          // 字符連體,value 為 NSNumber
NSKernAttributeName              // 字符間距,value 為 NSNumber
NSStrikethroughStyleAttributeName// 刪除線,value 為 NSNumber
NSUnderlineStyleAttributeName    // 下劃線,value 為 NSNumber
NSStrokeColorAttributeName       // 描邊顏色,value 為 UIColor
NSStrokeWidthAttributeName       // 描邊寬度,value 為 NSNumber
NSShadowAttributeName            // 陰影,value 為 NSShadow
NSTextEffectAttributeName        // 文字效果,value 為 NSString
NSAttachmentAttributeName        // 附屬(圖片),value 為 NSTextAttachment
NSLinkAttributeName              // 鏈接,value 為 NSURL 或 NSString
NSBaselineOffsetAttributeName    // 基線偏移,value 為 NSNumber
NSUnderlineColorAttributeName    // 下劃線顏色,value 為 UIColor
NSStrikethroughColorAttributeName// 刪除線顏色,value 為 UIColor
NSObliquenessAttributeName       // 字體傾斜
NSExpansionAttributeName         // 字體扁平化
NSVerticalGlyphFormAttributeName // 橫豎排(0 水平,1 垂直),value 為 NSNumber

實例:只給部分文字設置樣式

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"0元"];
[string setAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14]}
                range:NSMakeRange(string.length - 1, 1)];
etlbl.attributedText = string;

實例:逐個字符設置不同效果

NSString *content = @"內容太多,需要自適應才能解決問題,所以需要寫這個擴展類";

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:content];

[string addAttribute:NSFontAttributeName
               value:[UIFont systemFontOfSize:10]
               range:NSMakeRange(0, 1)];   // 字號

[string addAttribute:NSForegroundColorAttributeName
               value:[UIColor yellowColor]
               range:NSMakeRange(1, 1)];   // 文字顏色

[string addAttribute:NSBackgroundColorAttributeName
               value:[UIColor purpleColor]
               range:NSMakeRange(2, 1)];   // 背景色

[string addAttribute:NSUnderlineStyleAttributeName
               value:@(NSUnderlineStyleSingle)
               range:NSMakeRange(3, 1)];   // 下劃線

[string addAttribute:NSUnderlineColorAttributeName
               value:[UIColor redColor]
               range:NSMakeRange(3, 1)];   // 下劃線顏色

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 400, 200, 30)];
label.attributedText = string;
[self.view addSubview:label];

知識點 4:讓 UILabel 支持垂直方向對齊

iOS 原生的 UILabel 中,文字在垂直方向上只能居中。如果設計稿要求居上或居下對齊,就需要通過重寫兩個方法來實現。做法是把 UILabel 繼承一個子類:

#import <UIKit/UIKit.h>

typedef enum {
    VerticalAlignmentTop = 0,   // 默認
    VerticalAlignmentMiddle,
    VerticalAlignmentBottom,
} VerticalAlignment;

@interface myUILabel : UILabel {
  @private
    VerticalAlignment _verticalAlignment;
}

@property (nonatomic) VerticalAlignment verticalAlignment;

@end
#import "myUILabel.h"

@implementation myUILabel

@synthesize verticalAlignment = verticalAlignment_;

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.verticalAlignment = VerticalAlignmentMiddle;
    }
    return self;
}

- (void)setVerticalAlignment:(VerticalAlignment)verticalAlignment {
    verticalAlignment_ = verticalAlignment;
    [self setNeedsDisplay];
}

// 關鍵方法一:計算文字實際應該佔據的矩形
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {
    CGRect textRect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];

    switch (self.verticalAlignment) {
        case VerticalAlignmentTop:
            textRect.origin.y = bounds.origin.y;
            break;
        case VerticalAlignmentBottom:
            textRect.origin.y = bounds.origin.y + bounds.size.height - textRect.size.height;
            break;
        case VerticalAlignmentMiddle:
        default:
            textRect.origin.y = bounds.origin.y + (bounds.size.height - textRect.size.height) / 2.0;
    }
    return textRect;
}

// 關鍵方法二:按算好的矩形繪製
- (void)drawTextInRect:(CGRect)requestedRect {
    CGRect actualRect = [self textRectForBounds:requestedRect
                         limitedToNumberOfLines:self.numberOfLines];
    [super drawTextInRect:actualRect];
}

@end

使用方式(實現左上對齊):

lbl_mylabel = [[myUILabel alloc] initWithFrame:CGRectMake(20, 50, 150, 600)];

UIColor *color = [UIColor colorWithPatternImage:[UIImage imageNamed:@"halfTransparent.png"]];
lbl_mylabel.backgroundColor = color;
lbl_mylabel.textAlignment = NSTextAlignmentLeft;
lbl_mylabel.textColor = UIColor.whiteColor;
lbl_mylabel.lineBreakMode = NSLineBreakByWordWrapping;
lbl_mylabel.numberOfLines = 0;
[lbl_mylabel setVerticalAlignment:VerticalAlignmentTop];

[self addSubview:lbl_mylabel];

這個實現的精妙之處在於:它沒有重寫整個繪製流程,只是把系統原本會居中的矩形重新算了一遍,再交給父類去畫。核心就是這兩個方法——textRectForBounds:limitedToNumberOfLines: 負責算位置,drawTextInRect: 負責按位置繪製。理解了這一點,你也可以擴展出更多對齊方式,比如按基線對齊或者按百分比定位。

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