项目开发中KVC的简单应用

项目中有些时候使用KVC,可以节省很多的时间精力,实现快速开发

前一段时间有同学问我,能不能在不自定义UI的情况下,修改ActionSheet指定title的颜色,当时说很简单啊,Runtime获取实例变量列表,找到设置标题颜色的key,使用KVC就可以搞定.

备注

编译条件: Xcode7.3.1;Project Deployment Target:iOS8.0.

主要步骤

  1. 初始化一个ActionSheet.

    1
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"title" delegate:nil cancelButtonTitle:@"cancle" destructiveButtonTitle:@"destructive" otherButtonTitles:@"other",@"other1", nil];
  2. 获取实例变量列表,可以为NSObject添加一个Category方法,用于打印列表,具体实现如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    - (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));
    }
    }

    结果如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    name:_alertController------type:@"UIAlertController"
    name:_presenter------type:@"_UIAlertControllerShimPresenter"
    name:_retainedSelf------type:@"UIActionSheet"
    name:_actions------type:@"NSMutableArray"
    name:_cancelIndex------type:q
    name:_firstOtherButtonIndex------type:q
    name:_destructiveButtonIndex------type:q
    name:_actionSheetStyle------type:q
    name:_context------type:@
    name:_hasPreparedAlertActions------type:B
    name:_isPresented------type:B
    name:_alertControllerShouldDismiss------type:B
    name:_handlingAlertActionShouldDismiss------type:B
    name:_dismissingAlertController------type:B
    name:_delegate------type:@"<UIActionSheetDelegate>"**

    一看结果,好气哦,UIAlertController这个类是iOS8之后才允许使用的,算了,换用这个类重新打印一下吧,经过测试,UIAlertAction这个类含有可以设置标题的属性,属性列表大概是酱紫的:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    name:_checked------type:B
    name:_isPreferred------type:B
    name:_imageTintColor------type:@"UIColor"
    name:_titleTextColor------type:@"UIColor"
    name:_style------type:q
    name:_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:q
    name:__representer------type:@"<UIAlertActionViewRepresentation_Internal>"
    name:__alertController------type:@"UIAlertController"

    里面找一下,_titleTextColor就是它了.

  3. 找到了就试一下喽.

    1
    [ac1 setValue:[UIColor redColor] forKeyPath:@"_titleTextColor"];
  4. run一下,完美.

  5. 其他.
    通过第2步,可以看到在iOS8上使用UIActionSheet也是可以达到同样的效果的,因为其中有_actions可以得到一个UIAlertAction的数组,重复上述步骤即可完成,以后适配iOS7的应用越来越少了,不考虑iOS7的适配,使用KVC可以便捷地实现这种UI效果,还是不错的.