I am a beginner learner of UIKit. I tried to launch this code, which has to change label's text when the button is pressed. However I got error(
import UIKit
class ViewController: UIViewController {
var button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
var label = UILabel(frame: CGRect(x: 100, y: 300, width: 200, height: 100))
override func viewDidLoad() {
super.viewDidLoad()
button.backgroundColor = UIColor.green
button.addTarget(self, action: #selector(actionButton(label:)), for: .touchUpInside)
self.view.addSubview(button)
label.text = "Button is not pressed!"
self.view.addSubview(label)
}
@objc func actionButton(label: UILabel){
label.text = "Button is pressed!"
}
}
My error:
019-08-18 07:28:41.281998-0700 Testing[4211:230478] -[UIButton setText:]: unrecognized selector sent to instance 0x7fd04451f360
2019-08-18 07:28:41.288350-0700 Testing[4211:230478] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIButton setText:]: unrecognized selector sent to instance 0x7fd04451f360'
*** First throw call stack: ( 0 CoreFoundation 0x000000010a53e29b exceptionPreprocess + 331 1 libobjc.A.dylib 0x0000000108b94735 objc_exception_throw + 48 2 CoreFoundation 0x000000010a55cfa4 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132 3 UIKitCore 0x000000010cda4163 -[UIResponder doesNotRecognizeSelector:] + 287 4 CoreFoundation 0x000000010a542fb6 ___forwarding_ + 1446 5 CoreFoundation 0x000000010a544e88 _CF_forwarding_prep_0 + 120 6 Testing 0x000000010826d871 $S7Testing14ViewControllerC12actionButton5labelySo7UILabelC_tF + 113 7 Testing 0x000000010826d8cc $S7Testing14ViewControllerC12actionButton5labelySo7UILabelC_tFTo + 60 8 UIKitCore 0x000000010c9be7c3 -[UIApplication sendAction:to:from:forEvent:] + 83 9 UIKitCore 0x000000010caf6e85 -[UIControl sendAction:to:forEvent:] + 67 10 UIKitCore 0x000000010caf71a2 -[UIControl _sendActionsForEvents:withEvent:] + 450 11 UIKitCore 0x000000010caf60e6 -[UIControl touchesEnded:withEvent:] + 583 12 UIKitCore 0x000000010d1d1334 -[UIWindow _sendTouchesForEvent:] + 2729 13 UIKitCore 0x000000010d1d2a30 -[UIWindow sendEvent:] + 4080 14 UIKitCore 0x000000010c9d8e10 -[UIApplication sendEvent:] + 352 15 UIKitCore 0x000000010c9110d0 dispatchPreprocessedEventFromEventQueue + 3024 16 UIKitCore 0x000000010c913cf2 __handleEventQueueInternal + 5948 17 CoreFoundation 0x000000010a4a1b31 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION + 17 18 CoreFoundation 0x000000010a4a13a3 __CFRunLoopDoSources0 + 243 19 CoreFoundation 0x000000010a49ba4f __CFRunLoopRun + 1263 20 CoreFoundation 0x000000010a49b221 CFRunLoopRunSpecific + 625 21 GraphicsServices 0x00000001127111dd GSEventRunModal + 62 22 UIKitCore 0x000000010c9bd115 UIApplicationMain + 140 23 Testing 0x000000010826eb37 main + 71 24 libdyld.dylib 0x000000010bab1551 start + 1 ) libc++abi.dylib: terminating with
actionButton(label: UILabel)
change toactionButton(sender: UIButton)
. – vpoltave