【Swift】UIAlertControllerの使い方

 

 

完成図

 

↓Alert                                                               ↓ActionSheet

f:id:nekokichi_yos2:20181009184018p:plain
f:id:nekokichi_yos2:20181009184023p:plain



解説

 

・プロセス

AlertController(Alertの外見)を生成

AlertAction(Alertの中身)を生成

present(Alertを発信)する

 

・Alert:中央に表示

・ActionSheet:下に表示

・title:見出し

・message:本文,メッセージ

 

ストーリーボード

 

f:id:nekokichi_yos2:20181009184000p:plain

 

ソースコード

 

import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    func alert(style: UIAlertControllerStyle) {
        
        //アラートを生成
        let alertController = UIAlertController(title: "title", message: nil, preferredStyle: style)
        //アラートの選択肢を生成
        let action1 = UIAlertAction(title: "action1", style: .default){ (action: UIAlertAction) in
        }
        //アラートを使用可能に
        alertController.addAction(action1)
        
        
        let action2 = UIAlertAction(title: "action2", style: .default){ (action: UIAlertAction) in
        }
        alertController.addAction(action2)
        
        
        let cancelAction = UIAlertAction(title: "cancel", style: .cancel, handler: nil)
        alertController.addAction(cancelAction)
        
        //アラートを表示する
        present(alertController, animated: true, completion: nil)
        
    }
    
    @IBAction func tapActionSheetButton(_ sender: UIButton) {
        alert(style: .actionSheet)
    }
    
    @IBAction func tapAlertButton(_ sender: UIButton) {
        alert(style: .alert)
    }
    
}