先看看下面代碼:
UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:@"您確定要退出嗎?" preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
// do somethings...
}];
UIColor *color = [UIColor redColor];
[action2 setValue:color forKey:@"_titleTextColor"];
[alertVC addAction:action2];
UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//do something...
}];
[alertVC addAction:action3];
[self presentViewController:alertVC animated:YES completion:nil];
上面這段代碼在iPhone上運行時沒有問題的,但是在iPad上運行會崩潰,至于原因我也看不明白,只知道如果preferredStyle是設置的UIAlertControllerStyleActionSheet就會崩潰,但是如果preferredStyle設置成UIAlertControllerStyleAlert則不會奔潰;通過搜索發(fā)現(xiàn) 需要在模態(tài)之前加幾句代碼,
if ([alertVC respondsToSelector:@selector(popoverPresentationController)]) {
alertVC.popoverPresentationController.sourceView = self.view; //必須加
alertVC.popoverPresentationController.sourceRect = CGRectMake(0, kScreenHeight, kScreenWidth, kScreenHeight);//可選,我這里加這句代碼是為了調(diào)整到合適的位置
}
[self presentViewController:alertVC animated:YES completion:nil];
另外需要注意的是,在iPhone上 如果有多個UIAlertAction ,UIAlertAction的style可以是不同的,但是在iPad上如果兩個或者多個UIAlertAction的style不同,那么只會顯示一個。上面的情況可能是我的iPad系統(tǒng)比較老吧,9.3.5系統(tǒng)