先看看下面代碼:
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上運(yùn)行時(shí)沒(méi)有問(wèn)題的察皇,但是在iPad上運(yùn)行會(huì)崩潰超歌,至于原因我也看不明白脊串,只知道如果preferredStyle是設(shè)置的UIAlertControllerStyleActionSheet就會(huì)崩潰鹃答,但是如果preferredStyle設(shè)置成UIAlertControllerStyleAlert則不會(huì)奔潰篡撵;通過(guò)搜索發(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上 如果有多個(gè)UIAlertAction ,UIAlertAction的style可以是不同的音羞,但是在iPad上如果兩個(gè)或者多個(gè)UIAlertAction的style不同囱桨,那么只會(huì)顯示一個(gè)。上面的情況可能是我的iPad系統(tǒng)比較老吧嗅绰,9.3.5系統(tǒng)