2016-10-04 98 views
3

代码,我写了iOS9,效果非常好:UIAlertController背景颜色iOS10

UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Select source" 
                    message:nil 
                  preferredStyle:UIAlertControllerStyleActionSheet]; 
    alert.view.backgroundColor = DARK_BLUE; 
    alert.view.tintColor = NEON_GREEN; 
    UIView *subview = alert.view.subviews.firstObject; 
    UIView *alertContentView = subview.subviews.firstObject; 
    alertContentView.backgroundColor = DARK_BLUE; 
    alertContentView.layer.cornerRadius = 10; 

我的观点是,UIAlertControllerUIViewController继承和UIViewController有属性UIView是可以改变的。这是工作。现在,从UIViewController继承的视图有自己的子视图,contentView显示为Alert。我可以在子视图数组中以firstObject的形式访问它。现在,为什么消息发送背景颜色不再工作了?有谁知道一些新的解决方案?

+0

https://iosdevcenters.blogspot.com/2016/05/hacking-uialertcontroller-in-swift.html –

+0

谢谢你答案,但这里的解释是一样的,从子视图数组访问内容视图。它现在显示黄色模糊的颜色。不是原创的。 – Stefan

回答

13

为大家将碰到同样的问题,我已经找到了解决办法:

UIAlertController.view包含一个子视图,也就是只有容器

该子视图包含包含两个它自己的子视图子视图,一个是集装箱,并模糊它的另一个是层。

因此,它需要在循环中遍历这两个子视图并更改两者的背景颜色。

全码:

UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Select source" 
                    message:nil 
                  preferredStyle:UIAlertControllerStyleActionSheet]; 
    alert.view.tintColor = NEON_GREEN; 

    UIView *firstSubview = alert.view.subviews.firstObject; 

    UIView *alertContentView = firstSubview.subviews.firstObject; 
    for (UIView *subSubView in alertContentView.subviews) { //This is main catch 
     subSubView.backgroundColor = DARK_BLUE; //Here you change background 
    } 
+1

在iOS 10上工作。谢谢。 – iChirag

+0

不客气! – Stefan

0

我用这个:

UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Alert!" 
                     message:@"Message of alert" 
                   preferredStyle:UIAlertControllerStyleAlert]; 

     UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"Ok" 
                   style:UIAlertActionStyleDefault 
                   handler:^(UIAlertAction * action) { 

                    //Your code 
                   }]; 
     [alert addAction:defaultAction]; 

     UIView * topview = alert.view.subviews.firstObject; 
     UIView * colorView = topview.subviews.firstObject; 
     colorView.backgroundColor = [UIColor yellowColor]; 
     colorView.layer.cornerRadius = 10; 
     [self presentViewController:alert animated:YES completion:nil]; 
+0

对不起,但方法与我的示例代码非常相似。我试过了,它显示黄色,但模糊,我需要原创。 – Stefan

+0

然后我建议你实现你的自定义uialertcontroller,更快的方式 – Pol

+1

我找到了解决方案,检查我自己的答案,它可以帮助你碰到相同的问题。 – Stefan

3

在雨燕3.0

let FirstSubview = alertController.view.subviews.first 
    let AlertContentView = FirstSubview?.subviews.first 
    for subview in (AlertContentView?.subviews)! { 
     subview.backgroundColor = UIColor.black 
     subview.layer.cornerRadius = 10 
     subview.alpha = 1 
     subview.layer.borderWidth = 1 
     subview.layer.borderColor = UIColor.yellow.cgColor 
    }