在swift中创建一个简单的警报

Gok*_*lek 6 objective-c swift

看起来alertstatus不能在swift中使用.

你能帮助我实现下面代码的替代解决方案吗?

  [self alertStatus:@"Message!" :@"Alert title" :0];
Run Code Online (Sandbox Code Playgroud)

iPa*_*tel 11

尝试使用以下代码

let alert = UIAlertView()
alert.title = "Title"
alert.message = "My message"
alert.addButtonWithTitle("Ok")
alert.show()
Run Code Online (Sandbox Code Playgroud)

但是在iOS 8中

UIAlertView已弃用.因此,使用UIAlertControllerpreferredStyleUIAlertControllerStyleAlert.它应该是

var alert = UIAlertController(title: "Title", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)


Nic*_*der 8

XCODE 10、IOS 12 和 Swift 4 及更高版本:

1. 简单的警报视图,对警报中的按钮没有任何操作。

let alert = UIAlertController(title: "Error", message: "Something Went Wrong", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)

2.通过确定和取消按钮的操作发出警报:

let refreshAlert = UIAlertController(title: "Punch Out", message: "You Will Will Punch Out", preferredStyle: UIAlertController.Style.alert)

refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
            print("Handle Ok logic here")
   }))

refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
            print("Handle Cancel Logic here")
            refreshAlert .dismiss(animated: true, completion: nil)
   }))

    self.present(refreshAlert, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)

如需更多自定义,请参阅此StackOverflow 答案