user12388503
user12388503

Reputation:

Add target to UIButton inside UITableViewCell

I have UIButton inside my CustomTableViewCell and I also call addTarget:

let eyeButton: UIButton = {
    let v = UIButton()
    v.addTarget(self, action: #selector(eyeButtonTapped), for: .touchUpInside)
    v.setImage(UIImage(named: "eyeOpen"), for: .normal)
    v.translatesAutoresizingMaskIntoConstraints = false
    return v
}()

However this functions is not being called (also declared inside CustomTableViewCell):

@objc func eyeButtonTapped(){
    print("Hi")
}

There is a "tap-animation" when I click the button but nothing happens..

Anyone know why this happens and how I can fit it ?

Upvotes: 0

Views: 177

Answers (2)

testing
testing

Reputation: 101

Create Button Outlet Name cellbuttonName or anyother than write that code in tableviewdelegate cellForRowAtIndexPath

[self.cellbuttonName addTarget:self action:@selector(updateDate:) forControlEvents:UIControlEventTouchUpInside];

Upvotes: 0

DonMag
DonMag

Reputation: 77477

When declaring your button, self doesn't exist at that point.

Either add the target in your setup func, or change your declaration to a lazy var:

lazy var eyeButton: UIButton = {
    let v = UIButton()
    v.addTarget(self, action: #selector(eyeButtonTapped), for: .touchUpInside)
    v.setImage(UIImage(named: "eyeOpen"), for: .normal)
    v.translatesAutoresizingMaskIntoConstraints = false
    return v
}()

Upvotes: 1

Related Questions