2017-10-19 84 views
0

我使用swift 4來構建我的用戶界面,我創建了一個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) 

建立成功,但是當我點擊按鈕。

拋出一個錯誤

libc++abi.dylib: terminating with uncaught exception of type NSException

我知道它是可以改變的,以#selector(ViewClass.methodName)@objc func methodName() {..}方式。

但爲什麼Selector無法正常工作?這是一個正確的swift 4的方式?

+1

比較https://stackoverflow.com/q/44390378/2976878(欺騙?)。無論您使用'Selector'的初始化程序還是'#selector'(後者更可取),您都需要將'onClick(_:forEvent :))'暴露給Obj-C。目標行動是Obj-C模式;爲了查找實現以調用給定的選擇器,需要Obj-C運行時。 – Hamish

回答

0

你應該@objc前綴的功能,使其對Objective-C的運行時可見,例如:

@objc func onClick(_ sender: Any, forEvent event: UIEvent) 
+0

同樣以下列形式添加選擇器: '#selector(onClick(sender:event :))' – MrDEV

相關問題