我有一个设置,可以在单击按钮时打开日期选择器。我有两个a函数,可以在选择日期时更改按钮的值。此外,我还有一个功能,当我按下done按钮时,该功能可以帮助关闭日期选择器。但是,我继续收到一个错误,指出“无法识别的选择器发送到实例”。知道我可能做错了什么吗

 @IBOutlet weak var dueDateSelector: UIButton!
 @IBOutlet weak var myPickerView: UIPickerView!

@IBAction func changeDueDate(_ sender: Any) {
    //Create the view
    let inputView = UIView(frame: CGRect(x:0, y:420, width: self.view.frame.width, height: 240))
    var datePickerView  : UIDatePicker = UIDatePicker(frame: CGRect(x:0, y:40, width:0, height:0))
    datePickerView.datePickerMode = UIDatePickerMode.date
    inputView.addSubview(datePickerView) // add date picker to UIView
    let doneButton = UIButton(frame: CGRect(x:270, y:0, width:100, height:50))
    doneButton.setTitle("Done", for: UIControlState.normal)
    doneButton.setTitle("Done", for: UIControlState.highlighted)
    doneButton.setTitleColor(UIColor.black, for: UIControlState.normal)
    doneButton.setTitleColor(UIColor.gray, for: UIControlState.highlighted)
    inputView.addSubview(doneButton) // add Button to UIView
    doneButton.addTarget(self, action: "doneButton:", for: UIControlEvents.touchUpInside) // set button click event
    datePickerView.addTarget(self, action: Selector("handleDatePicker:"), for: UIControlEvents.valueChanged)
    view.addSubview(inputView)
    handleDatePicker(sender: datePickerView) // Set the date on start.

}

  @objc func handleDatePicker(sender: UIDatePicker) {
    let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
    dueDateSelector.setTitle(dateFormatter.string(from: sender.date), for: .normal)
}

@objc func doneButton(sender:UIButton)
{
    dueDateSelector.resignFirstResponder() // To resign the inputView on clicking done.
}

最佳答案

这是因为Swift和Objective C之间的命名方法不一致。这也是为什么您应该使用#selector语法而不是字符串编写选择器的原因。您需要更改此行:

datePickerView.addTarget(self, action: Selector("handleDatePicker:"), for: UIControlEvents.valueChanged)

选择器是一个客观的东西。如果你是用字符串写的,那么你需要用一种客观的C语言来写。在您的代码中,handleDatePicker实际上不是在目标C中称为handleDatePicker:,它可能类似于handleDatePickerWithSender:。这是因为在这里有一个sender参数,它成为了目标C眼中的WithSender部分。
这就是为什么我们喜欢这样编写选择器:
#selector(handleDatePicker)

不用担心参数,只要方法名。
datePickerView.addTarget(self, action: #selector(handleDatePicker), for: UIControlEvents.valueChanged)

此外,还需要更改这一行:
doneButton.addTarget(self, action: "doneButton:", for: UIControlEvents.touchUpInside)

应该是:
doneButton.addTarget(self, action: #selector(doneButton), for: UIControlEvents.touchUpInside)

10-06 10:02