Timo Cengiz
Timo Cengiz

Reputation: 3417

How to make didSelectRowAt IndexPath work with custom delegate

Alright, so i have a ViewController with a UITableView in it. Before moving on with the coding i read that in order to get actions from buttons or have a custom cell you can either use tags or use a more cleaner solution using protocol & delegates. Obviously i choose the latter one.

Now when i use a custom UITableViewCell which is called TableViewCellsDelegate in my class ViewController i need to replace it with UITableViewDelegate in the code below as you can see:

class ViewController: UIViewController , UITableViewDataSource, TableViewCellsDelegate{} ....

My problem is that i have this function that is now not being called:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("in here")
    if indexPath.row == 0 {
        if dateCellExpanded {
            dateCellExpanded = false
        } else {
            dateCellExpanded = true
        }
        tableView.beginUpdates()
        tableView.endUpdates()
    }
}

I doubt that if you choose to have a custom UITableViewCell you loose some of the delegate functions. There has to be some solution. Here is my TableViewCellsDelegate

protocol TableViewCellsDelegate : class {
    func bookTapped(_ sender: UIButton)
    func unbookTapped(_ sender: UIButton)
}

    class TableViewCells: UITableViewCell {


        @IBOutlet var bookButtonProperties: UIButton!

        @IBOutlet var unbookButtonProperties: UIButton!

        @IBOutlet var nameField: UITextField!
        @IBOutlet var numberField: UITextField!

        weak var delegate: TableViewCellsDelegate?

        @IBAction func bookPressed(_ sender: UIButton) {
            delegate?.bookTapped(sender)
        }

       @IBAction func unbookPressed(_ sender: UIButton) {
            delegate?.unbookTapped(sender)
        }
    }

Upvotes: 0

Views: 698

Answers (2)

Kopytchuk Serhii
Kopytchuk Serhii

Reputation: 1

Maybe it's better to make notification, I'm trying to make delegate Method, but this if you don't need to give parameters, as for me its better way to do this

extension Notification.Name {
    static let internetDown = Notification.Name("internetDown")
}

to subscribe

NotificationCenter.default.addObserver(self, selector: #selector(performDeinit), name: .internetDown, object: nil)

to send:

NotificationCenter.default.post(name: .internetDown, object: nil, userInfo: nil)

Upvotes: 0

cwilliamsz
cwilliamsz

Reputation: 718

You need to use UITableViewDelegate in place of TableViewCellsDelegate to work the didSelectRowAt.

If you have any questions call me back.

Upvotes: 1

Related Questions