IOS以编程方式创buildUIAlertViewController
我正在使用代码(没有故事板)的ViewController。 我试图添加和AlertController
我在.m中声明propery
@property (nonatomic, strong) UIAlertController *alertController;
并在loadview
方法中初始化
//alertviewController _alertController = [[UIAlertController alloc]initWithNibName:nil bundle:nil];
并在viewDidLoad
调用alertview:
_alertController = [UIAlertController alertControllerWithTitle:@"Error display content" message:@"Error connecting to server, no local database" preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { LandingPageViewController *viewController = [[LandingPageViewController alloc] initWithNibName:nil bundle:nil]; // viewController.showNavBarBackButton = YES; [[AppDelegate sharedAppDelegate].rootViewController cPushViewController:viewController]; }]; [_alertController addAction:ok]; [self presentViewController:_alertController animated:YES completion:nil];
我不知道为什么警报没有显示出来。 有些事情我的代码错了。 如何以编程方式设置和调用alertViewController
?
- (void)logoutButtonPressed { UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"Logout" message:@"Are You Sure Want to Logout!" preferredStyle:UIAlertControllerStyleAlert]; //Add Buttons UIAlertAction* yesButton = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) { //Handle your yes please button action here [self clearAllData]; }]; UIAlertAction* noButton = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) { //Handle no, thanks button }]; //Add your buttons to alert controller [alert addAction:yesButton]; [alert addAction:noButton]; [self presentViewController:alert animated:YES completion:nil]; }
而在Swift> = 3 :
let alertController = UIAlertController(title: "Some Error", message: "Pleas confirm?", preferredStyle: .alert) let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(defaultAction) self?.present(alertController, animated: true, completion: nil)
全局警报控制器,可在所有视图控制器中访问。
用您的函数创buildUIViewController的扩展,以显示具有所需参数参数的警报
extension UIViewController { func displayalert(title:String, message:String) { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction((UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in alert.dismiss(animated: true, completion: nil) }))) self.present(alert, animated: true, completion: nil) } }
现在从你的视图控制器调用这个函数:
class TestViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.displayalert(title: <String>, message: <String>) } }