Appearance Proxies & Layers

时间秒杀一切 提交于 2019-12-24 03:05:17

问题


Is it possible to use iOS 5 appearance proxies to refactor code that sets properties on layers?

_button.layer.cornerRadius = 5.0f;
_button.layer.borderWidth = 1.0f;
_button.layer.borderColor = [[UIColor blackColor] CGColor];
_button.layer.masksToBounds = YES;

回答1:


Nope.. Apple's says:

To support appearance customization, a class must conform to the UIAppearanceContainer protocol and relevant accessor methods must be marked with UI_APPEARANCE_SELECTOR.

http://developer.apple.com/library/ios/#documentation/uikit/reference/UIAppearance_Protocol/Reference/Reference.html

And UIButton does not.

EDIT: And UIButton does not have any methods marked with UI_APPEARANCE_SELECTOR.




回答2:


The accepted answer is not correct. You can set properties on layers, however, you need to subclass the view and expose the layer properties through accessors.

To illustrate, I'll use just one property from the question, cornerRadius:

Step 1: Implement a UIButton subclass.

#import <UIKit/UIKit.h>

@interface MyRoundedCornerButton : UIButton

@end

Step 2: Add a property tagged with UI_APPEARANCE_SELECTOR.

#import <UIKit/UIKit.h>

@interface MyRoundedCornerButton : UIButton

@property (readwrite, nonatomic) CGFloat cornerRadius UI_APPEARANCE_SELECTOR;

@end

Step 3: Implement the new class.

@implementation MyRoundedCornerButton

- (void)setCornerRadius:(CGFloat)cornerRadius
{
    self.layer.cornerRadius = cornerRadius;
}

@end

Step 4: Set the corner radius in the appearance proxy.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    ...
    [MyRoundedCornerButton appearance].cornerRadius = 10.0;
    ...
}

Step 5: Then in IB, (or wherever you define the creation of the View), set the custom view class to (or instantiate an instance of) MyRoundedCornerButton instead of UIButton.

Notes: I've done this to apply an easily changeable gradient background throughout my app. In my case, all view controllers' root view use a custom class. This custom class provides a CAGradientLayer through the +(Class)layerClass method. Then, I expose the colors and locations properties of the underlying gradient layer using the UI_APPEARANCE_SELECTOR tag. Setting it once on app initialization customizes the entire app. You could even expose the colors to the user to allow them to fully customize colors of various controls.



来源:https://stackoverflow.com/questions/8778696/appearance-proxies-layers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!