Swift 6での書き方
文字列でselectorを書くとメソッド名や引数の間違いが実行時エラーになることがあるよ。現在は@objcメソッドと#selectorを使うと、対象の存在をコンパイラでも確認できるよ。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import UIKit class TapExample: UIViewController { let textView = UITextView() override func viewDidLoad() { super.viewDidLoad() view.addSubview(textView) textView.frame = view.bounds let tap = UITapGestureRecognizer(target: self, action: #selector(doubleTapped(_:))) tap.numberOfTapsRequired = 2 textView.addGestureRecognizer(tap) } @objc func doubleTapped(_ sender: UITapGestureRecognizer) { print("ダブルタップされました") } } |
以下は旧バージョン当時の記録
unrecognized selector sent to instance というエラー。
問題があったコード
|
1 2 3 |
let tap = UITapGestureRecognizer(target: self, action: "doubleTapped") tap.numberOfTapsRequired = 2 textView.addGestureRecognizer(tap) |
修正したコード
|
1 2 3 |
let tap = UITapGestureRecognizer(target: self, action: "doubleTapped:") tap.numberOfTapsRequired = 2 textView.addGestureRecognizer(tap) |
doubleTapped → doubleTapped:
これでおk
