我一直在努力在Swift中创建UIAlertView,但由于某些原因,我无法获得正确的语句,因为我遇到了以下错误:

找不到"init"的重载,该重载接受提供的 论据

我是这样写的:

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

那就称它为我正在使用的:

button2Alert.show()

到目前为止,它正在崩溃,我似乎就是不能得到正确的语法.

推荐答案

来自UIAlertView个班级的学生:

//UIAlertView已弃用.将UIAlertController与 改为UIAlertControllerStyleAlert的首选样式

在iOS 8上,您可以执行以下操作:

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)

现在,UIAlertController是一个单独的类,用于在iOS 8上创建我们所知的UIAlertViewUIActionSheet并与之交互.

Edit:处理操作:

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.x:

let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: .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)

Ios相关问答推荐

在SwiftData中从@ Query创建可排序、有序和分组的数据

在SwiftUI中使用系统图像和色调创建圆形按钮

在iOS 17脉冲符号效果不起作用的情况下制作UIBarButtonItem动画(没有UIImageView)

如何在SwiftUI中顺时针和逆时针两个方向应用旋转效果?

如何在SwiftUI中为带有CornerRadius的矩形创建下边框?

如何根据SWIFT中的按钮点击更新文本值

安装新版本 XCode 15.0 后无法运行应用程序 XCode

iphone 11 和 iphone 12 对于相同的布局显示不同的结果

如何使用自定义数据源在本地react 本机 ios 应用程序中加载 Tradingview 小部件?

UIView 阴影不适用于自定义扩展

通过 Rosetta 打开模拟器 xcode 14 以修复滚动

SwiftUI:如何为 ScrollView 制作可拉伸(灵活)的粘性标题?

UICollectionView - 动态单元格高度?

'+entityForName: nil 不是合法的 NSManagedObjectContext 参数 - 核心数据

Xcode 4.1 致命错误:自构建预编译头文件后修改了 stdlib

如何从一个特定的视图控制器中隐藏导航栏

如何用 Swift 圆化 UILabel 的边缘

水平滚动 UICollectionView 时对齐单元格的中心

iOS 7 圆形框架按钮

如何在 iphone 屏幕中间显示活动指示器?