简体   繁体   中英

Create Instance of Subclass that requires NSCoder

I have created a subclass of UILabel, based on an example from here: UILabel doesn't show inputView . I am trying to create an instance of the label inside a class that subclasses UITableViewCell. The issue I am having is that to create an instance of DatePickerLabel it requires an NSCoder.

let dp = DatePickerLabel(coder: NSCoder) 

I have this in my class that subclasses UITableViewCell but it doesn't seem to ever be triggered, leading to a null pointer when I run it (I tried using a variable and then assigning it inside this code):

required public init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    print("triggered")
}

Any help is greatly appreciated, DatePickerLabel shown below!

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()
}

}

Cheers!

In the question you linked to, the initialisation function was initWithCoder because that it used to load views from a storyboard or nib. You are not doing that.

So, change your init to a “plain” one, like:

init() {
    super.init()

    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM