iOS-UIAlertController设置按钮颜色

iOS8之后弹出框通过UIAlertController实现,但是有的时候需要设置UIAlertAction的文字颜色,我们可以先获取内部属性,通过键值对的形式进行设置:

    unsigned int count=0;
    Ivar *ivars = class_copyIvarList([UIAlertAction class], &count);
    for (int i = 0; i<count; i++) {
        Ivar ivar = ivars[i];
        NSLog(@"%s------%s", ivar_getName(ivar),ivar_getTypeEncoding(ivar));
    }
FlyElephant.png

颜色设置

            NSString *title=NSLocalizedString(@"Objective-C", nil);
            NSString *tipContent=NSLocalizedString(@"FlyElephant", nil);
            UIAlertController *alertController=[UIAlertController alertControllerWithTitle:title message:tipContent preferredStyle:UIAlertControllerStyleAlert];
            UIColor *color=[UIColor redColor];
            UIAlertAction *sureAction=[UIAlertAction actionWithTitle:NSLocalizedString(@"确定", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            }];
            [sureAction setValue:color forKey:@"titleTextColor"];
            UIAlertAction *cancelAction=[UIAlertAction actionWithTitle:NSLocalizedString(@"取消", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
            }];
            [cancelAction setValue:color forKey:@"titleTextColor"];
            [alertController addAction:sureAction];
            [alertController addAction:cancelAction];
            [self presentViewController:alertController animated:YES completion:nil];
FlyElephant.png

提示:iOS 8.3 之前没有此属性,如果需要支持iOS8.3以下需要判断以下是否存在该属性,否则会发生崩溃~

推荐阅读更多精彩内容