I have read many tutorials and even the official Apple documentation and must not understand what is wrong with this code.
我读过很多教程,甚至是苹果官方文档,我不应该理解这段代码有什么问题。
var dueDatePicker = UIDatePicker()
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textField.inputView = dueDatePicker
dueDatePicker.addTarget(self, action: #selector(datePickerValueChanged(_:)), for: UIControlEvents.valueChanged)
}
func datePickerValueChanged(_ sender: UIDatePicker){
//Do Stuff
}
At runtime, I click on the textField and the UIDatePicker appears. The function that the selector points to is executed. As soon as I click a UI object outside of the UIDatePicker, the app crashes with this error:
在运行时,我单击textField,将出现UIDatePicker。选择器指向的函数被执行。当我点击UIDatePicker外的UI对象时,应用程序就会因为这个错误而崩溃:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[YourApp.PromiseViewController dueDateChanged:]: unrecognized selector sent to instance 0x100b12ae0'
由于未被发现的异常“NSInvalidArgumentException”而终止应用程序,原因:PromiseViewController dueDateChanged:]::无法识别的选择器发送给实例0x100b12ae0'
What I don't understand is that the "selector" or pointer to the desired function is recognized initially. However, when I trigger another event from another UI Object this exception is thrown.
我不明白的是,“选择器”或指向所需函数的指针最初是被识别的。然而,当我从另一个UI对象触发另一个事件时,这个异常被抛出。
Why is this happening?
为什么会这样?
Shouldn't this exception be triggered when datePickerValueChanged()
is called initially?
当datePickerValueChanged()最初被调用时,不应该触发这个异常吗?
2 个解决方案
#1
5
The error is telling you that an action with the selector dueDateChanged(_:)
has been added as a target action.
错误是告诉您一个带有选择器dueDateChanged(_:)的操作被添加为目标操作。
More than one target action can be added to a control. Somewhere, maybe in your storyboard or xib, you have another action added to dueDatePicker
.
可以将多个目标操作添加到控件中。在某个地方,可能在您的故事板或xib中,您有另一个动作添加到dueDatePicker。
#2
8
Just add @objc in front of your function
只需在函数前面添加@objc
@objc func datePickerValueChanged(_ sender: UIDatePicker){
//Do Stuff
}
#1
5
The error is telling you that an action with the selector dueDateChanged(_:)
has been added as a target action.
错误是告诉您一个带有选择器dueDateChanged(_:)的操作被添加为目标操作。
More than one target action can be added to a control. Somewhere, maybe in your storyboard or xib, you have another action added to dueDatePicker
.
可以将多个目标操作添加到控件中。在某个地方,可能在您的故事板或xib中,您有另一个动作添加到dueDatePicker。
#2
8
Just add @objc in front of your function
只需在函数前面添加@objc
@objc func datePickerValueChanged(_ sender: UIDatePicker){
//Do Stuff
}