斗士狗 2014-06-03 18:35 采纳率: 0%
浏览 644
已采纳

如何在 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

  • 写回答

29条回答 默认 最新

  • from.. 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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(28条)

报告相同问题?

悬赏问题

  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥20 为什么我写出来的绘图程序是这样的,有没有lao哥改一下
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?