2016-10-04 94 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 
    }