Change Text Color of Items in UIActionSheet - iOS 8

Salman Zaidi picture Salman Zaidi · Jun 11, 2014 · Viewed 42.8k times · Source

I had been using following code to change text color of items which I add in UIActionSheet.:

- (void)willPresentActionSheet:(UIActionSheet *)actionSheet {
    for (UIView *subview in actionSheet.subviews) {
        if ([subview isKindOfClass:[UIButton class]]) {
            UIButton *button = (UIButton *)subview;
            [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
    }
}

It works fine in iOS7, but in iOS8 the above code doesn't change the text color of items.

Now my question is how to change the text color of items which I add in UIActionSheet using iOS8??

Additional Info:
I added breakpoint to see whether following lines from the above code get executed or not:

UIButton *button = (UIButton *)subview;
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

These lines do not get executed. So, if([subview isKindOfClass:[UIButton class]]) is always false for all items of actionSheet.subviews. So what I think is that the view heirarchy of UIActionSheet has been changed.

Answer

nonamelive picture nonamelive · Nov 6, 2014

There's an easy way if you still want to use UIActionSheet instead of UIAlertController in order to support older iOS versions.

UIActionSheet actually uses UIAlertController in iOS 8, and it has a private property _alertController.

SEL selector = NSSelectorFromString(@"_alertController");
if ([actionSheet respondsToSelector:selector])
{
    UIAlertController *alertController = [actionSheet valueForKey:@"_alertController"];
    if ([alertController isKindOfClass:[UIAlertController class]])
    {
        alertController.view.tintColor = [UIColor blueColor];
    }
}
else
{
    // use other methods for iOS 7 or older.
}

For Swift Below code should works

let alertAction = UIAlertAction(title: "XXX", style: .default) { (action) in

     }

    alertAction.setValue(UIColor.red, forKey: "titleTextColor")