我得创造一些日期-时间在我的应用程序中选择程序,所以我想创建一个效用类返回可重用的UIDateTimePicker我将在整个应用程序中使用。每个挑选者将有一个取消和已完成按钮中的工具栏
问题 对于应该发生的操作,请点击取消和已完成,我正在考虑使用这样的闭包:
func createDatePicker(isDateTime: Bool, doneAction: ()->(), cancelAction: ()->()) -> UIDatePicker {
// Code for setting up the dateTime picker
// Deciding the picker mode for the picker
dateTimePicker.datePickerMode = isDateTime ? UIDatePicker.Mode.dateAndTime : UIDatePicker.Mode.date
// Creating a toolbar for the Picker
let toolbar = UIToolbar()
toolbar.sizeToFit()
// Creating buttons for toolbar
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.done, target: self, action: #selector(doneAction)) // ---- ERROR -----
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.plain, target: self, action: #selector(cancelAction)) // ---- ERROR -----
// Adding buttons to the toolbar
toolbar.setItems([cancelButton,spaceButton,doneButton], animated: false)
// Adding the Toolbar to the dateTimePicker and returning the dateTimePicker
}
现在,当我尝试将闭包添加为按钮的操作时,就会出现问题,因为它们不是选择器(与@objc附在上面)
我得到的错误是
“选择器”的参数不能引用参数“所做的操作”
如何处理此问题,或者是否有另一种方法将要执行的代码从主(ViewController)类传递给此实用程序类(在取消和完成时)
class Closure {
let closure: ()->()
init (_ closure: @escaping ()->()) {
self.closure = closure
}
@objc func action () {
closure()
}
}
extension UIBarButtonItem {
public convenience init(title: String?, style: UIBarButtonItem.Style, action: @escaping ()->()) {
let handle = Closure(action)
self.init(title: title, style: style, target: handle, action: #selector(Closure.action))
objc_setAssociatedObject(self, "ex_action", handle, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItem.Style.done, action: dor
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。