零零乙 2014-06-03 18:35 采纳率: 33.3%
浏览 828
已采纳

如何在 Swift 中创建一个 UIAlertView?

I have been working to create a UIAlertView in Swift, but for some reason I can't get the statement right because I'm getting this error:

Could not find an overload for 'init' that accepts the supplied arguments

Here is how I have it written:

let button2Alert: UIAlertView = UIAlertView(title: "Title", message: "message",
                     delegate: self, cancelButtonTitle: "OK", otherButtonTitles: nil)

Then to call it I'm using:

button2Alert.show()

As of right now it is crashing and I just can't seem to get the syntax right.

转载于:https://stackoverflow.com/questions/24022479/how-would-i-create-a-uialertview-in-swift

  • 写回答

30条回答 默认 最新

  • 乱世@小熊 2014-06-03 18:48
    关注

    From the UIAlertView class:

    // UIAlertView is deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead

    On iOS 8, you can do this:

    let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))
    self.presentViewController(alert, animated: true, completion: nil)
    

    Now UIAlertController is a single class for creating and interacting with what we knew as UIAlertViews and UIActionSheets on iOS 8.

    Edit: To handle actions:

    alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { action in
        switch action.style{
        case .Default:
            print("default")
    
        case .Cancel:
            print("cancel")
    
        case .Destructive:
            print("destructive")
        }
    }}))
    

    Edit for Swift 3:

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

    Edit for Swift 4:

    let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
          switch action.style{
          case .default:
                print("default")
    
          case .cancel:
                print("cancel")
    
          case .destructive:
                print("destructive")
    
    
    }}))
    self.present(alert, animated: true, completion: nil)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(29条)

报告相同问题?

悬赏问题

  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 github训练的模型参数无法下载
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案
  • ¥50 winform中使用edge的Kiosk模式
  • ¥15 关于#python#的问题:功能监听网页
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题