LoginSignup
9
8

More than 3 years have passed since last update.

[Swift4]アラートを表示 Display Alert

Last updated at Posted at 2018-03-22

Swift初心者ですが、どんどん発信していこうと思います。

今回は、「アラートを表示」させてみました。

まず、ボタンをMain.storyboardに作ります。

(Xcodeの右下で"button"と検索すれば、すぐ見つかります。)

Screen Shot 2018-03-22 at 14.28.06.png

「アラートを表示」という名前にしてみました。
次に、Xcode右上の○が2つ重なっているボタン

"Show the assistant editor"をクリック

ViewControllerの一番下らへんにコネクトします。
(「アラートを表示」からcontrolを押しながらドラッグ&ドロップです。)

Screen Shot 2018-03-22 at 14.26.15.png

Connection: Action
Name: displayAlert
Type: UIButton
Event: Touch Up Inside
Arguments: None
に設定します。

次に、その中身を編集していきます。

ViewController.swift
import UIKit

class ViewController: UIViewController {
    //@IBOutlet weak var imageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // 今回の「アラートを表示」はここから
    @IBAction func displayAlert() {
        let title = "アラートテスト"
        let message = "タップしてくれてサンクス."
        let okText = "ok"

        let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
        let okayButton = UIAlertAction(title: okText, style: UIAlertActionStyle.cancel, handler: nil)
        alert.addAction(okayButton)

        present(alert, animated: true, completion: nil)
    }
    // 今回の「アラートを表示」はここまで
}

最後に、Xcodeの左上の実行ボタンでビルドしてみましょう。

Screen Shot 2018-03-22 at 14.29.07.png

しっかり、アラートは表示されましたか?^_^

9
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8