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

时间:2014-06-07 14:35:48

标签: objective-c swift

看起来 alertstatus 无法在swift中使用。

你们可以帮我实现下面代码的替代解决方案吗?

  [self alertStatus:@"Message!" :@"Alert title" :0];

4 个答案:

答案 0 :(得分:11)

尝试使用以下代码

let alert = UIAlertView()
alert.title = "Title"
alert.message = "My message"
alert.addButtonWithTitle("Ok")
alert.show()

但是在 iOS 8

UIAlertView已弃用。因此,UIAlertController使用preferredStyle UIAlertControllerStyleAlert。它应该是

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)

答案 1 :(得分:2)

你可以这样做3行。确保添加"确定"按钮或"动作"这将有助于解除警报,否则你最终会在警报中冻结屏幕

    let myMessage = "This is an alert"

    let myAlert = UIAlertController(title: myMessage, message: nil, preferredStyle: UIAlertControllerStyle.Alert)

    myAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))

    self.presentViewController(myAlert, animated: true, completion: nil)

答案 2 :(得分:2)

Swift 3 iOS 10

 let alert = UIAlertController(title: "Title", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
            alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
            self.present(alert, animated: true, completion: nil)

答案 3 :(得分:0)

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)

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)

更多自定义信息,请参见此StackOverflow Answer