Kev
Kev

Reputation: 181

Swift - Button action not triggered in table view cell

I have a ViewController who contains a TableView. I want in each cell, a red button who did something (let's say 'hello' for test), or when I touch the cell anywhere but not on the button I perform a segue.

But even when I touch the button, it's the segue who perform. I tried some search on SF but none of the questions help me...

I don't know if that's usual but when I touch the cell, all the row white background become gray, even the background of the red button.

In storyboard I have this cell hierarchy :

hierarchy of the cell

The user interaction is enabled on both cell and button.

In the questions I found they said, on the cell set 'accessory' on 'disclosure indicator', I did it, but if it's possible I would like to keep it at 'None'. Also I set a custom class for the cell, here is the code :

class MyTableViewCell: UITableViewCell {   
@IBOutlet weak var rentButton: UIButton? // I use this class for 2 tableview almost similar, but in the other I don't have the redButton, that's why I put an '?'
}

I also set the delegate and datasource of the tableView to my ViewController, here is the code of my view controller :

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! MyTableViewCell

    cell.rentButton!.tag = indexPath.row
    cell.rentButton!.addTarget(self, action: #selector(MyViewController.rent(_:)), forControlEvents: .TouchUpInside)

    return cell
}
// Rent() is never called:
func rent(sender: UIButton) {
    print("here \(sender.tag)")
}

EDIT : The solution was to put out the button from the conainer view !

Upvotes: 1

Views: 1137

Answers (1)

Ben Sullivan
Ben Sullivan

Reputation: 2154

You can stop the segue from actioning when the button is pressed by performing it programatically. You can do the following:

  1. Remove your segue that goes from the cell to another view controller and change it go from the TableViewController to the other view controller

  2. Create a variable in your TableViewController class such as: var buttonPressed = false

  3. In your button action set buttonPressed to true

  4. In didSelectRow, check that buttonPressed is not true then performSegue and change buttonPressed to false, else do nothing

  5. As discussed, move the button from the container to the content view

Upvotes: 1

Related Questions