私はswift 4
を使用してUIを構築します。UIButton
を作成し、ターゲットを追加します。xcode 9.0.1/swift 4、Objective-Cセレクタで宣言されたメソッドがありませんonClick:forEvent: '
しかし、コンパイラが警告を投げる:No method declared with Objective-C selector 'onClick:forEvent:'
button.addTarget(self, action: Selector("onClick:forEvent:"), for: UIControlEvents.touchUpInside)
//...
func onClick(_ sender: Any, forEvent event: UIEvent) {
print("button click", sender, event);
}
私は警告の三角形をクリックしてこの問題を解決しようとします。 Wrap the selector name in parentheses to suppress this warning
。
括弧内にセレクタ名をラップするだけです。
button.addTarget(self, action: Selector(("onClick:forEvent:")), for: UIControlEvents.touchUpInside)
ビルドに成功しましたが、ボタンをクリックしたときに成功しました。
は、私はそれが#selector(ViewClass.methodName)
と@objc func methodName() {..}
方法に変更することができます知っているエラー
libc++abi.dylib: terminating with uncaught exception of type NSException
を投げます。
しかし、なぜSelector
が機能しないのですか?これは正しいswift 4
ですか?
は(だます?)https://stackoverflow.com/q/44390378/2976878を比較してください。 'Selector'の初期化子か'#selector'を使うかどうかにかかわらず、 'onClick(_:forEvent:)'をObj-Cに公開する必要があります。ターゲットアクションはObj-Cパターンです。指定されたセレクタを呼び出すために実装をルックアップするためには、Obj-Cランタイムが必要です。 – Hamish