Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton doesn't work on a custom UITableViewCell (Swift)

I'm really sorry for my english and if I make something wrong, and this is my first question here.

I have a custom UITableViewCell as a view in *.xib file. with an UIImage in it and a button on that UIImage. I connected this button with an outlet to my CustomTableViewCell.swift class.

@IBOutlet weak var authorImage: UIImageView!
@IBOutlet weak var authorButton: UIButton!

In the MyTableViewController.swift I've registered a nib

tableView.registerNib(UINib(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "my_cell")

And wrote an cellForRow... function like this:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("my_cell", forIndexPath: indexPath) as! CustomTableViewCell
    cell.authorButton.addTarget(self, action: "authorButtonPressed:", forControlEvents: .TouchUpInside)
    return cell
}

And, finally I have this function (which I use in addTarget...):

func authorButtonPressed (sender:UIButton!) {
    print("Hi!")//line1
    print(sender)
}

and a breakpoint on the first line. But this function is never called.

And I have also just understood that button isn't animated, when I tap it.

How can I fix it or find a way to the solution?

Thank you in advance

like image 568
Nikolay Pryahin Avatar asked Jan 22 '26 15:01

Nikolay Pryahin


1 Answers

You are using a UIView as the root view in your nib. For a custom UITableViewCell you need to make the root view a UITableViewCell:

enter image description here

So, you have to create an empty xib and than drag a UITableViewCell on it. Then start adding your subviews to the ContentView

like image 74
joern Avatar answered Jan 24 '26 08:01

joern