简体   繁体   中英

Create a customized table view cell using swift

I am following this tutorial http://www.raywenderlich.com/62435/make-swipeable-table-view-cell-actions-without-going-nuts-scroll-views to create a customized table cell. But I am using swift instead of objective c.

Here is my table cell view in swift.

protocol SwipeableCellDelegate {
    func buttonOneActionForItemText(itemText: NSString)
    func buttonTwoActionForItemText(itemText: NSString)
}

class MyTableViewCell: UITableViewCell {
    @IBOutlet weak var button1: UIButton!
    @IBOutlet weak var button2: UIButton!
    @IBOutlet weak var mytextLabel: UILabel!

    @IBOutlet weak var testLabel: UILabel!

    var delegate: SwipeableCellDelegate

    init(delegate: SwipeableCellDelegate) {
        self.delegate = delegate
        super.init()
    }

    required init(coder aDecoder: NSCoder) {
       // fatalError("init(coder:) has not been implemented")
        super.init(coder : aDecoder)
    }
}

But it does not compile, I get error saying:

MyTableViewCell.swift:38:9: Property 'self.delegate' not initialized at super.init call

And if I get rid of "init(coder aDecoder: NSCoder)", I get error saying 'required' initializer 'init(coder:)' must be provided by subclass of UITableViewCell'.

I have read this thread Class does not implement its superclass's required members

about what to do in my required init(coder aDecoder: NSCoder).

But I can't get the code to compile.

I appreciate if someone can help me.

Thank you.

It's saying you need to have delegate defined at the end of all init methods, because that class variable is not set as an optional. One approach would be to make it optional (meaning it can be nil)

var delegate: SwipeableCellDelegate?

Read about initialization and Optional Property Types here

There are 3 ways to tackle your problem, of varying beauty and amounts of hassle.

  1. If you just need the code to compile, but will never use the required init from coder, you can just leave the default error in there.

  2. Also you can make the delegate field optional, but you will need to handle the theoretical possibility of a nil in your code from now on. Like this:

    var delegate: SwipeableCellDelegate?

    guard let dlgt = delegate else {print("Delegate is not set for this cell"); return}

  3. Or you can define a default value for a delegate somewhere public and set it in the required 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