2017-09-24 56 views
1

當更新項目代碼到swift 4得到一些錯誤的add.target方法 我該如何解決這個錯誤?如何更新addTarget方法swift 4

//swift3 

var chatLogController: ChatLogController? { 
    didSet { 
     sendButton.addTarget(chatLogController, action: #selector(ChatLogController.handleSend), for: .touchUpInside) 

     uploadImageView.addGestureRecognizer(UITapGestureRecognizer(target: chatLogController, action: #selector(ChatLogController.handleUploadTap))) 
    } 
} 
+0

「得到一些錯誤」獲取_what_錯誤? – matt

+0

這個錯誤「#selector'的參數是指實例方法'handleSend()'沒有公開到Objective-C」 –

+1

那麼你的答案。只要閱讀錯誤信息說的是什麼!把'@ objc'放在'func handleSend ...'前面(你甚至沒有在你的問題中顯示,看在上帝的份上)。 – matt

回答

5

提示信息告訴你該怎麼做,在聲明你的函數之前添加@obj

@objc func handleSend(_ sender: UIGestureRecognizer){ 
    ... 
} 

的原因是因爲:

在Objective-C,選擇器是指 Objective-C的方法的名稱的類型。在Swift中,Objective-C選擇器由 ,Selector結構表示,並且可以使用#selector 表達式構造。要爲可以從 Objective-C調用的方法創建選擇器,請傳遞方法的名稱,例如 #selector(MyViewController.tappedButton(_:))。要爲屬性的Objective-C getter或setter方法構造選擇器,請傳遞 屬性名稱,前綴爲getter:setter:標籤,例如 #selector(getter: MyViewController.myButton)

查看更多here,在蘋果文檔。

+0

對於剛開始使用Swift編碼的人來說,這是一個很好的答案。人們應該像這樣越來越少的批評回答:) –

+0

@RoiMulia,謝謝。 –

+0

@HabibAlejalil,哪個錯誤,你使用Swift 4? –