简体   繁体   中英

Swift4 - UIButton use addTarget in UIView with error

This is code with addTarget in required init in UIVIew

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

this is my select function

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

when I click the button in UIView then application crashes with error :

TeachSystem[27065:8131674] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[TeachSystem.CameraView hiddenCameraAction:]: unrecognized selector sent to instance 0x121d11050' * First throw call stack: (0x1ee830ec4 0x1eda01a40 0x1ee749c24 0x21bb74558 0x1ee8367dc 0x1ee83848c 0x21bb48454 0x21b5d5d0c 0x21b5d602c 0x21b5d502c 0x21bb81bac 0x21bb82e10 0x21bb6210c 0x21bc30f68 0x21bc33960 0x21bc2c450 0x1ee7c11f0 0x1ee7c1170 0x1ee7c0a54 0x1ee7bb920 0x1ee7bb1f0 0x1f0a34584 0x21bb46d40 0x105039f40 0x1ee27abb4) libc++abi.dylib: terminating with uncaught exception of type NSException

Question : How to resolve this error?

操作应定义为#selector

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

All you need to do is to put string into parentheses.

action: ("hiddenCameraAction:")

... however, this is deprecated way how to achieve what you need to achieve.


I would recommend you to start using selector which is safer since compiler provides you error immediately and code won't run with bad method name or whatever.

Syntax is: #selector(method(externalParameter:))


在此处输入图片说明

... you can just start typing and compiler will suggest you what Objective-C method you can put inside

action: #selector(hiddenCameraAction(_:))

Action should be defined as #selector and the function should have an @objc inference.

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

hiddenCameraAction function

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

The @objc inference allows the hiddenCameraAction method be accessible to the Objective-C runtime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM