簡體   English   中英

Swift4-UIButton在UIView中使用addTarget錯誤

[英]Swift4 - UIButton use addTarget in UIView with error

這是UIVIew中required init中帶有addTarget的代碼

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    hiddenButton = self.viewWithTag(9000) as? UIButton
    hiddenButton.addTarget(self, action: "hiddenCameraAction:", for: .touchUpInside)
}

這是我的選擇功能

func hiddenCameraAction(_ sender: Any)  {
    //Do something
}

當我單擊UIView的按鈕時,應用程序崩潰並顯示錯誤:

TeachSystem [27065:8131674] *由於未捕獲的異常'NSInvalidArgumentException'而終止應用程序,原因:'-[TeachSystem.CameraView hiddenCameraAction:]:無法識別的選擇器已發送到實例0x121d11050'*第一個拋出調用堆棧:(0x1ee830ec4 0x1eda01a40 0x1ee749c480 0481 0x21b5d5d0c 0x21b5d602c 0x21b5d502c 0x21bb81bac 0x21bb82e10 0x21bb6210c 0x21bc30f68 0x21bc33960 0x21bc2c450 0x1ee7c11f0 0x1ee7c1170 0x1ee7c0a54 0x1ee7bb920 0x1ee7bb1f0 0x1f0a34584 0x21bb46d40 0x105039f40 0x1ee27abb4)的libc ++ abi.dylib:與類型NSException的未捕獲的異常終止

問題:如何解決此錯誤?

操作應定義為#selector

hiddenButton.addTarget(self, action: #selector(hiddenCameraAction(_:)), for: .touchUpInside). 

您需要做的就是將字符串放在括號中。

action: ("hiddenCameraAction:")

...但是,這是過時的方式,無法實現您需要實現的目標。


我建議您開始使用選擇器,該選擇器更安全,因為編譯器會立即為您提供錯誤,並且代碼不會以錯誤的方法名稱或任何其他方式運行。

語法為: #selector(method(externalParameter:))


在此處輸入圖片說明

...您可以開始輸入內容,編譯器會建議您可以放入哪種Objective-C方法

action: #selector(hiddenCameraAction(_:))

應將動作定義為#selector ,並且函數應具有@objc推斷。

hiddenButton.addTarget(self, action: #selector(hiddenCameraAction(_:)), for: .touchUpInside)

hiddenCameraAction函數

@objc func hiddenCameraAction(_ sender: Any)  {
    //Do something
}

@objc推論允許hidden-CameraAction方法可被Objective-C運行時訪問。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM