您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發基礎

自定義系統控件外觀:深入 UIAppearance

編輯:iOS 開發基礎

文章開頭,先引用 Mattt Thompson 大神在 UIAppearance 裡的一句話:

Users will pay a premium for good-looking software.

就像大多數人都愛看帥哥美女一樣,一款 App 能否被接受,「長得怎樣」至關重要。雖然大家都懂「人不可貌相」的道理,但多數人終究還是視覺動物。用戶體驗也好、用戶感受也罷,如果連讓用戶看得舒心都做不到,又何談體驗呢?所以……哎,我也只能在這默默碼字了。

在 iOS 5 之前,想自定義系統控件的外觀是一件頗為頭疼的事。若要統一改變系統控件的外觀,我們可能得絞盡腦汁想各種辦法,比如設法繼承現有的控件類並在子類中修改,甚至動用 method swizzling 這類「高大上」的手段。好在蘋果從 iOS 5 起提供了一種全新的方式——UIAppearance,讓這一切簡單了不少。下面就來系統地梳理一下。

UIAppearance 的作用

UIAppearance 實際上是一個協議,我們可以透過它獲取某個類的外觀代理(appearance proxy)。之所以說是「類」而非明確的「視圖或控件」,是因為有些非視圖對象(如 UIBarButtonItem)也能實現該協議,用來定義其所包含視圖的外觀。我們可以向這個類的外觀代理發送修改消息,來自定義該類所有實例的外觀。

以系統控件 UIButton 為例,依使用方式的不同,我們既能透過 UIAppearance 修改整個應用中所有 UIButton 的外觀,也能只修改某個特定容器類中所有 UIButton 的外觀(如 UIBarButtonItem)。需要注意的是,這種修改只會影響那些在執行 UIAppearance 操作之後才被添加到視圖層級中的對象,而不會影響修改之前就已加入的對象。因此,若要修改特定視圖,請務必確保該視圖是在使用 UIAppearance 之後才透過 addSubview 加入視圖層級的。

UIAppearance 的使用

如前所述,自定義外觀有兩種方式:針對某類的所有實例;針對包含在某一容器類實例中的某類實例。有點繞口,我把文檔原文貼出來:

for all instances, and for instances contained within an instance of a container class.

為此,UIAppearance 聲明了兩個方法。若想自定義某類所有實例的外觀,可用:

// swift
static func appearance() -> Self
// Objective-C
+ (instancetype)appearance

例如,要修改所有 UINavigationBar 實例的背景色與標題外觀,可以這樣寫:

UINavigationBar.appearance().barTintColor = UIColor(red: 104.0/255.0, green: 224.0/255.0, blue: 231.0/255.0, alpha: 1.0)
UINavigationBar.appearance().titleTextAttributes = [
    NSFontAttributeName: UIFont.systemFontOfSize(15.0),
    NSForegroundColorAttributeName: UIColor.whiteColor()
]

我們也可以指定一類容器,在該容器內自定義某類所有實例的外觀,方法如下:

+ (instancetype)appearanceWhenContainedIn:(Class<UIAppearanceContainer>)ContainerClass, ...

比如要修改導航欄中所有按鈕的外觀,可這樣處理:

[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil]
    setBackgroundImage:myNavBarButtonBackgroundImage forState:state barMetrics:metrics];
[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], [UIPopoverController class], nil]
    setBackgroundImage:myPopoverNavBarButtonBackgroundImage forState:state barMetrics:metrics];
[[UIBarButtonItem appearanceWhenContainedIn:[UIToolbar class], nil]
    setBackgroundImage:myToolbarButtonBackgroundImage forState:state barMetrics:metrics];
[[UIBarButtonItem appearanceWhenContainedIn:[UIToolbar class], [UIPopoverController class], nil]
    setBackgroundImage:myPopoverToolbarButtonBackgroundImage forState:state barMetrics:metrics];

注意,這個方法的參數是可變參數,因此可以一次設置多個容器。

仔細翻看文檔會發現,這個方法沒有 Swift 版本——至少我在 iOS 8.x 的 SDK 裡沒找到對應方法。想在 iOS 8.x 以下用 Swift 調用 appearanceWhenContainedIn,就只能老老實實用混編了。

不過到了 iOS 9 的 SDK(記錄一下,今天是 2015.07.18),這個方法又被補了回來,只不過參數換成了數組:

@available(iOS 9.0, *)
static func appearanceWhenContainedInInstancesOfClasses(containerTypes: [AnyObject.Type]) -> Self

嗯,這裡有個問題。我在 Xcode 7.0 beta 3 上測試這個 Swift 方法時,把它放進了啟動方法裡:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // 此處會崩潰,提示 EXC_BAD_ACCESS
    let barButtonItemAppearance = UIBarButtonItem.appearanceWhenContainedInInstancesOfClasses([UINavigationBar.self])
    let attributes = [
        NSFontAttributeName: UIFont.systemFontOfSize(13.0),
        NSForegroundColorAttributeName: UIColor.whiteColor()
    ]
    barButtonItemAppearance.setTitleTextAttributes(attributes, forState: .Normal)
    return true
}

程序崩潰了,在 appearanceWhenContainedInInstancesOfClasses 這一行提示 EXC_BAD_ACCESS。既然是內存問題,那就排查一番。我做了以下幾個測試:

1. 拆分 UIBarButtonItem.appearanceWhenContainedInInstancesOfClasses,在它前面加了幾行:

let appearance = UIBarButtonItem.appearance()
let arr: [AnyObject.Type] = [UINavigationBar.self, UIToolbar.self]
print(arr)

結果顯示,除了 appearanceWhenContainedInInstancesOfClasses 本身,其他幾個元素都沒問題。

2. 把這段拷到默認的 ViewController 中運行,同樣崩潰。

3. 在相同環境下(Xcode 7.0 beta 3 + iOS 9.0),改用 Objective-C 的對應方法試了試:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UINavigationBar class]]];
    return YES;
}

程序很順利地跑了起來。

呃,我能把這歸結為版本不穩定的緣故嗎?還是等正式版出來後再研究吧。

支援 UIAppearance 的組件

從 iOS 5.0 起,已有大量 iOS API 支援 UIAppearance 代理方法。Mattt Thompson 在 UIAppearance 中提供了以下兩行腳本,可獲取所有標註了 UI_APPEARANCE_SELECTOR 的方法:

$ cd /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;//'

大家可以親自試試。這裡列出部分輸出:

./UIActivityIndicatorView.h:@property (readwrite, nonatomic, retain) UIColor *color NS_AVAILABLE_IOS(5_0) UI_APPEARANCE_SELECTOR;
./UIAppearance.h:/* To participate in the appearance proxy API, tag your appearance property selectors in your header with UI_APPEARANCE_SELECTOR.
./UIAppearance.h:#define UI_APPEARANCE_SELECTOR __attribute__((annotate("ui_appearance_selector")))
./UIBarButtonItem.h:- (void)setBackgroundImage:(UIImage *)backgroundImage forState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics NS_AVAILABLE_IOS(5_0) UI_APPEARANCE_SELECTOR;
......

大家也可以去查看 iOS 7.0 下的完整清單。

自定義類實現 UIAppearance

我們可以自定義一個類並讓它支援 UIAppearance。為此需要做兩件事:

  1. 讓我們的類實現 UIAppearanceContainer 協議。

  2. 若在 Objective-C 中,則用 UI_APPEARANCE_SELECTOR 標記相關方法;而在 Swift 中,需在對應的屬性或方法前加上 dynamic。

當然,若希望我們的類能用 appearance(或 appearanceWhenContainedInInstancesOfClasses)獲取自身類,還需實現 UIAppearance 協議。

這裡我們定義一個帶邊框的 Label,透過 UIAppearance 設置它的默認邊框。由於 UIView 本身已實現了 UIAppearance 與 UIAppearanceContainer 協議,因此在其子類中我們不必再顯式聲明實現這兩個接口。

Label 的聲明如下:

// RoundLabel.h
@interface RoundLabel : UILabel
@property (nonatomic, assign) CGFloat borderWidth UI_APPEARANCE_SELECTOR;
@property (nonatomic, assign) CGFloat cornerRadius UI_APPEARANCE_SELECTOR;
@property (nonatomic, assign) UIColor *borderColor UI_APPEARANCE_SELECTOR;
@end

具體實現如下:

@implementation RoundLabel
- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    self.layer.borderColor = _borderColor.CGColor;
    self.layer.cornerRadius = _cornerRadius;
    self.layer.borderWidth = _borderWidth;
}
- (void)setBorderWidth:(CGFloat)borderWidth {
    _borderWidth = borderWidth;
}
- (void)setCornerRadius:(CGFloat)cornerRadius {
    _cornerRadius = cornerRadius;
}
- (void)setRectColor:(UIColor *)rectColor {
    _borderColor = rectColor;
}
@end

我們在 drawRect: 中設置 Label 的邊框,這樣 RoundLabel 的所有實例就能使用默認的邊框配置屬性了。

接著,可以在 AppDelegate 或其他位置設置 RoundLabel 的默認配置:

UIColor *color = [UIColor colorWithRed:104.0/255.0 green:224.0/255.0 blue:231.0/255.0 alpha:1.0f];
[RoundLabel appearance].cornerRadius = 5.0f;
[RoundLabel appearance].borderColor = color;
[RoundLabel appearance].borderWidth = 1.0f;

當然,使用 RoundLabel 時,還可依實際需要再修改這幾個屬性的值。

Swift 的實現則簡單得多,只需這樣處理:

class RoundLabel: UILabel {
    dynamic func setBorderColor(color: UIColor) {
        layer.borderColor = color.CGColor
    }
    dynamic func setBorderWidth(width: CGFloat) {
        layer.borderWidth = width
    }
    dynamic func setCornerRadius(radius: CGFloat) {
        layer.cornerRadius = radius
    }
}

在 UIAppearanceContainer 的官方文檔中,對支援 UIAppearance 的方法有格式限制,具體要求如下:

// Swift
func propertyForAxis1(axis1: IntegerType, axis2: IntegerType, axisN: IntegerType) -> PropertyType
func setProperty(property: PropertyType, forAxis1 axis1: IntegerType, axis2: IntegerType)
// OBJECTIVE-C
- (PropertyType)propertyForAxis1:(IntegerType)axis1 axis2:(IntegerType)axis2 … axisN:(IntegerType)axisN;
- (void)setProperty:(PropertyType)property forAxis1:(IntegerType)axis1 axis2:(IntegerType)axis2 … axisN:(IntegerType)axisN;

其中屬性類型可以是 iOS 的任意類型,包括 id、NSInteger、NSUInteger、CGFloat、CGPoint、CGSize、CGRect、UIEdgeInsets 或 UIOffset;而 IntegerType 必須是 NSInteger 或 NSUInteger,類型不對則會拋出異常。

以 UIBarButtonItem 為例,它定義了以下符合格式的方法:

setTitlePositionAdjustment:forBarMetrics:
backButtonBackgroundImageForState:barMetrics:
setBackButtonBackgroundImage:forState:barMetrics:

Trait Collection

翻閱 UIAppearance 的官方文檔,可以看到 iOS 8 之後,這個協議又新增了兩個方法:

// Swift
static func appearanceForTraitCollection(_ trait: UITraitCollection) -> Self
// Objective-C
+ (instancetype)appearanceForTraitCollection:(UITraitCollection *)trait
+ (instancetype)appearanceForTraitCollection:(UITraitCollection *)trait
                          whenContainedIn:(Class<UIAppearanceContainer>)ContainerClass, ...

這兩個方法涉及 Trait Collection,具體內容在此不做過多分析。

一些更深入的東西

了解怎麼用 UIAppearance 之後,我們再來看看它背後是如何運作的,思路參照 UIAppearance for Custom Views 一文。

在以下實現中打一個斷點:

- (void)setBorderWidth:(CGFloat)borderWidth {
    _borderWidth = borderWidth;
}

然後運行程序。啟動時,雖然 AppDelegate 中調用了:

[RoundLabel appearance].borderWidth = 1.0f;

但此時程序並沒有在斷點處停下。等進入 Label 所在的視圖控制器時,程序才在斷點處停住。這時我們可以觀察方法的調用棧。

在調用棧裡,我們能看到 _UIAppearance 這個傢伙,可從 iOS-Runtime-Headers 中找到它的定義:

@interface _UIAppearance : NSObject {
    NSMutableArray *_appearanceInvocations;
    NSArray *_containerList;
    _UIAppearanceCustomizableClassInfo *_customizableClassInfo;
    NSMapTable *_invocationSources;
    NSMutableDictionary *_resettableInvocations;
}

其中 _UIAppearanceCustomizableClassInfo 存儲的是外觀對應類的信息,其聲明如下:

@interface _UIAppearanceCustomizableClassInfo : NSObject {
    NSString *_appearanceNodeKey;
    Class _customizableViewClass;
    Class _guideClass;
    unsigned int _hash;
    BOOL _isCustomizableViewClassRoot;
    BOOL _isGuideClassRoot;
}
@end

在 _UIAppearance 中還有一個 _appearanceInvocations 變量,我們可以在 Debug 中嘗試用以下命令打印它的信息:

po [[NSClassFromString(@"_UIAppearance") _appearanceForClass:[RoundLabel class] withContainerList:nil] valueForKey:@"_appearanceInvocations"]

可以得到這樣的結果:

<__NSArrayM 0x7fd44a5c1f80>(
    NSInvocation: 0x7fd44a5c1d20   return value: {v} void target: {@} 0x10b545ae0 selector: {:} setCornerRadius: argument 2: {d} 0.000000
    NSInvocation: 0x7fd44a5bf300   return value: {v} void target: {@} 0x10b545ae0 selector: {:} setBorderColor: argument 2: {@} 0x7fd44a5bbb80
    NSInvocation: 0x7fd44a50b8c0   return value: {v} void target: {@} 0x10b545ae0 selector: {:} setBorderWidth: argument 2: {d} 0.000000
)

可以看到,這個數組裡存儲的其實是 NSInvocation 對象,每個對象對應的就是我們在程序中設置 RoundLabel 外觀的方法信息。

Peter Steinberger 的文章中提到,當我們設置了一個自定義外觀時,_UIAppearanceRecorder 會去保存並跟蹤這個設置。它的聲明如下:

@interface _UIAppearanceRecorder : NSObject {
    NSString *_classNameToRecord;
    NSArray *_containerClassNames;
    NSMutableArray *_customizations;
    Class _superclassToRecord;
    NSArray *_unarchivedCustomizations;
}

不過有點可惜的是,我沒能從這裡挖到太多信息。我用 runtime 檢查了這個類的數據,看上去沒啥東西,可能是姿勢不對,我把代碼和結果貼出來,大家幫我看看:

unsigned int outCount = 0;
Class recorderClass = NSClassFromString(@"_UIAppearanceRecorder");
id recorder = [recorderClass performSelector:NSSelectorFromString(@"_sharedAppearanceRecorderForClass::whenContainedIn:") withObject:[RoundLabel class] withObject:nil];
NSLog(@"_UIAppearanceRecorder instance : %@", recorder);
Ivar *variables = class_copyIvarList(recorderClass, &outCount);
for (int i = 0; i < outCount; i++) {
    Ivar variable = variables[i];
    id value = object_getIvar(recorder, variable);
    NSLog(@"variable's name: %s, value: %@", ivar_getName(variable), value);
}
free(variables);

打印結果:

_UIAppearanceRecorder instance : <_UIAppearanceRecorder: 0x7fa29a718960>
variable's name: _classNameToRecord, value: RoundLabel
variable's name: _superclassToRecord, value: (null)
variable's name: _containerClassNames, value: (null)
variable's name: _customizations, value: ( )
variable's name: _unarchivedCustomizations, value: (null)

回過頭再看 _UIAppearance 的 _appearanceInvocations,我們是否可以大膽猜測:UIAppearance 是否透過類似 Swizzling Method 的方式,在運行時動態更新視圖的默認顯示呢?求解答。

遺留問題

這一篇留下了兩個懸而未決的問題:

  1. 在 Swift 中該如何正確使用 appearanceWhenContainedInInstancesOfClasses 方法?我在 Stack Overflow 上沒找到答案。

  2. iOS 內部究竟是如何利用 UIAppearance 保存的信息,在運行時替換默認設置的?

若有答案,還請不吝告知。

小結

使用 UIAppearance,我們可以很方便地修改一些視圖或控件的默認顯示。同樣地,如果打算開發一個視圖庫,也可能用得上相關知識——在庫的內部自定義一些 UIAppearance 規則,代替手動逐一修改外觀,這樣庫的使用者就能透過 UIAppearance 整體地調整某一類視圖的外觀。

我在 GitHub 上搜索 UIAppearance 相關實例時,發現了 UISS 這個開源庫,它提供了一種便捷的方式來定義程序樣式,同樣基於 UIAppearance。依其介紹,若想自定義一個 UIButton 的外觀,可以這樣寫:

{
    "UIButton":{
        "titleColor:normal":["white", 0.8],
        "titleColor:highlighted":"white",
        "backgroundImage:normal": ["button-background-normal", [0,10,0,10]],
        "backgroundImage:highlighted": ["button-background-highlighted", [0,10,0,10]],
        "titleEdgeInsets": [1,0,0,0],
        "UILabel":{
            "font":["Copperplate-Bold", 18]
        }
    }
}

看著像 JSON 吧?具體的我也還沒細看,回頭抽空再研究研究這個庫。

補充:文章中的示例代碼已放到 GitHub 中,可以在這裡查看(不保證在 iOS 9.0 以下能正常運行,嘿嘿)。

參考

  • UIAppearance

  • UIAppearance Protocol Reference

  • UIAppearanceContainer Protocol Reference

  • UIAppearance for Custom Views

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