【Xcode/Swift】画面下半分にアラート画面を表示させる


Storyboard


コード記述

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet private weak var alertLabel: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    @IBAction func showAlertAction(_ sender: Any) {
        showAlert()
    }
    
    // アラートを表示する
    private func showAlert() {
        // UIAlertControllerを用意する
        let actionAlert = UIAlertController(title: "Fish or Beef", message: "どちらかを選んでください", preferredStyle: UIAlertController.Style.actionSheet)
        
        // Fishを選択したときのアクション
        let kabigonAction = UIAlertAction(title: "Fish", style: UIAlertAction.Style.default, handler: {
            (action: UIAlertAction!) in
            self.alertLabel.text = "Fish Please"
            print("Fishを選択")
        })
        actionAlert.addAction(kabigonAction)
        
        // Beefを選択したときのアクション
        let pikachuAction = UIAlertAction(title: "Beef", style: UIAlertAction.Style.default, handler: {
            (action: UIAlertAction!) in
            self.alertLabel.text = "Beef Please"
            print("Beefを選択")
        })
        actionAlert.addAction(pikachuAction)
        
        // Cancelを選択したときのアクション
        let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: {
            (action: UIAlertAction!) in
            self.alertLabel.text = "キャンセルしました"
            print("Cancelします")
        })
        actionAlert.addAction(cancelAction)
        
        // アラート表示
        self.present(actionAlert, animated: true, completion: nil)
        
    }
    
}

この記事は役に立ちましたか?

はい
いいえ
貴重なフィードバックありがとうございます!