UIAppearance学习和使用
2018-05-04 本文已影响8人
Maj_sunshine
我们可以通过UIAppearance协议的方法来给整个项目中某一类控件添加全局样式,或者项目中某个类的子类控件添加全局样式。
使用举例
/**
全局UI设置
*/
- (void)globalSettingUI {
if (@available(iOS 11.0, *)) {
[[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
[[UITableView appearance] setEstimatedRowHeight:0];
[[UITableView appearance] setSectionFooterHeight:0];
[[UITableView appearance] setSectionHeaderHeight:0];
}
[[UITableView appearance] setShowsVerticalScrollIndicator:NO];
[[UITableView appearance] setBackgroundColor:kAppBackGroundColor];
[[UICollectionView appearance] setBackgroundColor:kAppBackGroundColor];
[[UICollectionViewCell appearance] setBackgroundColor:[UIColor whiteColor]];
}
[UIActivityIndicatorView appearanceWhenContainedInInstancesOfClasses:@[[MBProgressHUD class]]].color = [UIColor whiteColor];
UIBarButtonItem *barItem;
if (@available(iOS 9.0, *)) {
barItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
} else {
barItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
}
什么控件能使用UIAppearance协议的方法
遵循UIAppearance协议的类,才能使用协议中的方法。
例如
NS_CLASS_AVAILABLE_IOS(2_0) @interface UIBarItem : NSObject <NSCoding, UIAppearance>
NS_CLASS_AVAILABLE_IOS(2_0) @interface UIView : UIResponder <NSCoding, UIAppearance, UIAppearanceContainer, UIDynamicItem, UITraitEnvironment, UICoordinateSpace, UIFocusItem, CALayerDelegate>
可以知道UIView和UIBarItem是遵循UIAppearance协议的,那么UIView和UIBarItem的子类也是可以使用UIAppearance协议中的方法。当然还有其他的类也遵循。
一般使用的方法
+ (instancetype)appearance;
// iOS9以下
+ (instancetype)appearanceWhenContainedIn:(nullable Class <UIAppearanceContainer>)ContainerClass, ... NS_REQUIRES_NIL_TERMINATION NS_DEPRECATED_IOS(5_0, 9_0, "Use +appearanceWhenContainedInInstancesOfClasses: instead") __TVOS_PROHIBITED;
// iOS9以上
+ (instancetype)appearanceWhenContainedInInstancesOfClasses:(NSArray<Class <UIAppearanceContainer>> *)containerTypes NS_AVAILABLE_IOS(9_0);
让某一类控件同时约束
// UITableView不显示垂直线
[[UITableView appearance] setShowsVerticalScrollIndicator:NO];
// 全部按钮显示白色
[[UIButton appearance] setBackgroundColor:[UIColor whiteColor]];
让一种控件在另一种控件中表现某种属性
// 获取TZImagePickerController 中的UIBarButtonItem类控件,设置
UIBarButtonItem *barItem;
if (@available(iOS 9.0, *)) {
barItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
} else {
barItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
}
NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
textAttrs[NSForegroundColorAttributeName] = self.barItemTextColor;
textAttrs[NSFontAttributeName] = self.barItemTextFont;
[barItem setTitleTextAttributes:textAttrs forState:UIControlStateNormal];