零零乙 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 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试