天天看點

UIAppearance使用方法

定義

UIAppearance是一個協定,用來在全局視角中設定類屬性。例如,在應用啟動的方法裡面寫下:

[[UILabel appearance] setBackgroundColor:[UIColor orangeColor]];
           

在以後的任何地方使用UILabel,其backgroundColor都是orangeColor。

系統中遵守UIAppearance協定的類及方法

在終端中輸入以下指令,進入到Headers檔案下:

/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS*.sdk/System/Library/Frameworks/UIKit.framework/Headers

執行以下指令即可檢視系統中所有支援的類、屬性和方法:

grep -H UI_APPEARANCE_SELECTOR ./* | sed ‘s/ __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_5_0) UI_APPEARANCE_SELECTOR;//’

隻有調用列出的來的這些屬性、方法才會産生效果。

自定義遵守UIAppearance協定的類

自定義了一個繼承自UILabel的類ALLabel,由于UIView預設遵守了UIAppearance協定,則無需在ALLabel中申明。在屬性或方法後面加上UI_APPEARANCE_SELECTOR标示,表示可以通過Appearance來更改外觀。

ALLabel.h

#import <UIKit/UIKit.h>

@interface ALLabel : UILabel

@property (nonatomic, copy) UIColor *txtColor UI_APPEARANCE_SELECTOR;

- (void)printTxtColor UI_APPEARANCE_SELECTOR;

@end
           

ALLabel.m

#import "ALLabel.h"

@implementation ALLabel

- (void)printTxtColor {
    NSLog(@"%@", _txtColor);
}

@end
           

在其他地方使用UIAppearance就可以更改外觀了:

ViewController.m

#import "ViewController.h"
#import "ALLabel.h"

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [ALLabel appearance].txtColor = [UIColor redColor];
}

@end
           

至此,在這個方法以後的任何地方,執行個體化的任何ALLabel對象都具備紅色的字型。

點選這裡檢視示例