DRYな備忘録

Don't Repeat Yourself.

【iOS】ボタン長押しの実装【Xcode10.3】【Swift5】

Xcodeは変化が早いので記事の日付に注意してください

ゴール

  • 長押ししてアラートとか出るボタンを設置する

tl;dr

override func viewDidLoad() {
    super.viewDidLoad()
    let recognizer = UILongPressGestureRecognizer(target: self, action: #selector(onLongPress))
    self.button.addGestureRecognizer(recognizer)
}

@objc func onLongPress() {
    let alert = UIAlertController(title: "Long Press", message: "親父にも長押しされたことないのに!", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
    self.present(alert, animated: true, completion: nil)
}

以下読まなくていいです。

1. ボタンの設置・追加

最近のXcodeはオブジェクトの追加をするペインが無い。Cmd + Shif + Lで、かつてオブジェクト選択のペインだったものがダイアログとして出てくる。

f:id:otiai10:20190808105440p:plain
Cmd + Shift + L

ここで、ButtonをStoryboardにドラッグアンドドロップして、適当にテキスト変えて、終了。

f:id:otiai10:20190808105756p:plain

2. 通常のTouchイベントの登録

Storyboardを表示した状態で、右上の「◯◯」を押すと、Storyboardに紐付いているViewControllerが反面に開かれる。

f:id:otiai10:20190808110042p:plain

で、ButtonとViewControllerを紐付ける。

f:id:otiai10:20190808110925p:plain

ちょっとAlert出すコード書く。

@IBAction func onTouchDownButton(_ sender: Any) {
    let alert = UIAlertController(title: "Touch Down", message: "押したねっ", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "close", style: .default, handler: nil))
    self.present(alert, animated: true, completion: nil)
}

こうなる

f:id:otiai10:20190808112127g:plain

3. 長押しのRecognizerを設置

とりあえずさっき作って紐付けたTouch Downイベントは消して、以下のようなコードを書く。

このとき、self.buttonは、上記のような要領で、Ctrl押しながらUIパーツをViewControllerにひっぱってきて置いたもの。

override func viewDidLoad() {
    super.viewDidLoad()
    let recognizer = UILongPressGestureRecognizer(target: self, action: #selector(onLongPress))
    self.button.addGestureRecognizer(recognizer)
}

// func onLongPress(_ sender: UILongPressGestureRecognizer) {
@objc func onLongPress() {
    let alert = UIAlertController(title: "Long Press", message: "親父にも長押しされたことないのに!", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
    self.present(alert, animated: true, completion: nil)
}

こうなる

f:id:otiai10:20190808114936g:plain

雑感

  • Xcodeは補完がきもちいいですね
  • Swiftはguardが好きです
  • iOS開発たのしい

DRYな備忘録として