简体   繁体   中英

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

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:

在此处输入图片说明

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

You shouldn't add add target on this function:

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
}

You just add outlet action into your cell. It will be fine. Like this code:

@IBAction func testPressed(sender: AnyObject) {
    print("test")
}

按照 joern 解决方案,然后通过单击它来选择Table View Cell ,并确保应启用属性检查器窗格的User Interaction Enabled属性的复选标记。

Did you use this magic button? 在此处输入图片说明

Thanks to it you can see your layer tree and it might content something weird... like this. 在此处输入图片说明

A view over the rest of them which is doing mess there. Just investigate, mate! 😎

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