我已根据此处的示例创建了UILabel的子类:UILabel doesn't show inputView。我试图在UITableViewCell的子类中创建一个标签实例。我遇到的问题是,要创建一个DatePickerLabel实例,它需要一个NSCoder。
let dp = DatePickerLabel(coder: NSCoder)
我在我的类中有UITableViewCell的子类,但它似乎永远不会被触发,当我运行它时会导致空指针(我尝试使用变量然后在此代码中分配它):
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
print("triggered")
}
非常感谢任何帮助,DatePickerLabel如下所示!
class DatePickerLabel: UILabel {
private let _inputView: UIView? = {
let picker = UIDatePicker()
return picker
}()
private let _inputAccessoryToolbar: UIToolbar = {
let toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.default
toolBar.isTranslucent = true
toolBar.sizeToFit()
return toolBar
}()
override var inputView: UIView? {
return _inputView
}
override var inputAccessoryView: UIView? {
return _inputAccessoryToolbar
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(doneClick))
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
_inputAccessoryToolbar.setItems([ spaceButton, doneButton], animated: false)
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(launchPicker))
self.addGestureRecognizer(tapRecognizer)
}
override var canBecomeFirstResponder: Bool {
return true
}
@objc private func launchPicker() {
becomeFirstResponder()
}
@objc private func doneClick() {
resignFirstResponder()
}
}
干杯!
答案 0 :(得分:0)
在您链接的问题中,初始化函数为initWithCoder
,因为它用于从故事板或笔尖加载视图。你不这样做。
因此,将init
更改为“普通”,例如:
init() {
super.init()
...
}