SwiftでUIAlertViewを作成するにはどうすればいいですか? 質問する

SwiftでUIAlertViewを作成するにはどうすればいいですか? 質問する

Swift で UIAlertView を作成しようとしていますが、何らかの理由で次のエラーが発生し、ステートメントを正しく実行できません。

指定された引数を受け入れる 'init' のオーバーロードが見つかりませんでした

私の書き方は次の通りです:

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

次に、それを呼び出すために次を使用します:

button2Alert.show()

現時点ではクラッシュしており、構文を正しく理解できないようです。

ベストアンサー1

クラスからUIAlertView:

// UIAlertView は非推奨です。代わりに UIAlertControllerStyleAlert の preferredStyle を指定したUIAlertControllerを使用してください

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)

現在は、iOS 8 でおよびUIAlertControllerと呼ばれていたものを作成および操作するための単一のクラスです。UIAlertViewUIActionSheet

編集:アクションを処理するには:

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")
    }
}}))

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)

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)

おすすめ記事