项目中有些时候使用KVC,可以节省很多的时间精力,实现快速开发
前一段时间有同学问我,能不能在不自定义UI的情况下,修改ActionSheet指定title的颜色,当时说很简单啊,Runtime获取实例变量列表,找到设置标题颜色的key,使用KVC就可以搞定.
备注
编译条件: Xcode7.3.1;Project Deployment Target:iOS8.0.
主要步骤
初始化一个ActionSheet.
1UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"title" delegate:nil cancelButtonTitle:@"cancle" destructiveButtonTitle:@"destructive" otherButtonTitles:@"other",@"other1", nil];获取实例变量列表,可以为NSObject添加一个Category方法,用于打印列表,具体实现如下:
123456789- (void)printIvarList{unsigned int count = 0;Ivar *ivars = class_copyIvarList([self class], &count);for (int i = 0; i<count; i++) {Ivar ivar = ivars[i];NSLog(@"name:%s------type:%s", ivar_getName(ivar),ivar_getTypeEncoding(ivar));}}结果如下:
123456789101112131415name:_alertController------type:@"UIAlertController"name:_presenter------type:@"_UIAlertControllerShimPresenter"name:_retainedSelf------type:@"UIActionSheet"name:_actions------type:@"NSMutableArray"name:_cancelIndex------type:qname:_firstOtherButtonIndex------type:qname:_destructiveButtonIndex------type:qname:_actionSheetStyle------type:qname:_context------type:@name:_hasPreparedAlertActions------type:Bname:_isPresented------type:Bname:_alertControllerShouldDismiss------type:Bname:_handlingAlertActionShouldDismiss------type:Bname:_dismissingAlertController------type:Bname:_delegate------type:@"<UIActionSheetDelegate>"**一看结果,好气哦,
UIAlertController
这个类是iOS8之后才允许使用的,算了,换用这个类重新打印一下吧,经过测试,UIAlertAction
这个类含有可以设置标题的属性,属性列表大概是酱紫的:123456789101112131415name:_checked------type:Bname:_isPreferred------type:Bname:_imageTintColor------type:@"UIColor"name:_titleTextColor------type:@"UIColor"name:_style------type:qname:_handler------type:@?name:_simpleHandler------type:@?name:_image------type:@"UIImage"name:_shouldDismissHandler------type:@?name:__descriptiveText------type:@"NSString"name:_contentViewController------type:@"UIViewController"name:_keyCommandInput------type:@"NSString"name:_keyCommandModifierFlags------type:qname:__representer------type:@"<UIAlertActionViewRepresentation_Internal>"name:__alertController------type:@"UIAlertController"里面找一下,_titleTextColor就是它了.
找到了就试一下喽.
1[ac1 setValue:[UIColor redColor] forKeyPath:@"_titleTextColor"];run一下,完美.
- 其他.
通过第2步,可以看到在iOS8上使用UIActionSheet
也是可以达到同样的效果的,因为其中有_actions可以得到一个UIAlertAction
的数组,重复上述步骤即可完成,以后适配iOS7的应用越来越少了,不考虑iOS7的适配,使用KVC可以便捷地实现这种UI效果,还是不错的.