How to change UIAlertController button text colour in iOS9?

后端 未结 14 1267
隐瞒了意图╮
隐瞒了意图╮ 2020-12-15 16:16

The question is similar to iOS 8 UIActivityViewController and UIAlertController button text color uses window's tintColor but in iOS 9.

I have a UIAlertControlle

相关标签:
14条回答
  • 2020-12-15 17:00

    I found a solution to this. Not an elegant solution, but a solution.

    I swizzled viewWillAppear: on UIAlertController, then looped through the views and modified the tint color. In my case I had a tintColor set on the entire window and despite setting the tintColor via appearance the UIAlertController maintained the color on the window. I check if the color is equal to that of the window and if so apply a new one. Blindly applying the tintColor to all views will result in the red tint on destructive actions to be reset.

    + (void)load  
    {  
        static dispatch_once_t onceToken;  
        dispatch_once(&onceToken, ^{  
            Method swizzleMethod = class_getInstanceMethod(self, @selector(viewWillAppear:));  
            Method method = class_getInstanceMethod(self, @selector(alertSwizzle_viewWillAppear:));  
            method_exchangeImplementations(method, swizzleMethod);  
        });  
    }  
    
    - (void)alertSwizzle_viewWillAppear:(BOOL)animated  
    {  
        [self alertSwizzle_viewWillAppear:animated];  
        [self applyTintToView:self.view];  
    }  
    
    - (void)applyTintToView:(UIView *)view  
    {  
        UIWindow *mainWindow = [UIApplication sharedApplication].keyWindow;  
    
        for (UIView *v in view.subviews) {  
            if ([v.tintColor isEqual:mainWindow.tintColor]) {  
                v.tintColor = [UIColor greenColor];  
            }  
            [self applyTintToView:v];  
        }  
    }  
    

    However this doesn't work on iOS 8, so you'll still need to set the apperance tint color.

    [[UIView appearanceWhenContainedIn:[UIAlertController class], nil] setTintColor:[UIColor greenColor]];  
    
    0 讨论(0)
  • 2020-12-15 17:03

    You have 3 styles for the action buttons:

    let style : UIAlertActionStyle = .default
    // default, cancel (bold) or destructive (red)
    
    let alertCtrl = UIAlertController(....)
    alertCtrl.addAction( UIAlertAction(title: "click me", style: style, handler: {
        _ in doWhatever()
    }))
    
    0 讨论(0)
提交回复
热议问题