crispy2k12 crispy2k12 - 4 months ago 14
Swift Question

UIbutton in UItableview with different actions for each button in each cell

In my

UITableView
I'm attempting to have a button that will have a different action for each cell i.e. links to different
viewController
, for each button but i've only managed to achieve it with one.

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return courseTitle.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomCell

cell.image_view.image = courseImages[indexPath.row]
cell.title.text = courseTitle[indexPath.row]
cell.tableButton.tag = indexPath.row
cell.tableButton.addTarget(self, action: "Test", forControlEvents: UIControlEvents.TouchUpInside)

return cell
}

@IBAction func Test(sender: AnyObject){

self.performSegueWithIdentifier("SuccessfulLogin", sender: nil)

}

Answer

You can use that tag value for that and change your selector syntax also

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomCell

    cell.image_view.image = courseImages[indexPath.row]
    cell.title.text = courseTitle[indexPath.row]
    cell.tableButton.tag = indexPath.row
    cell.tableButton.addTarget(self, action: "test:", forControlEvents: UIControlEvents.TouchUpInside)

    return cell
}

@IBAction func test(sender: UIButton){

    let row = sender.tag
    switch(row) {
        case 0:
            self.performSegueWithIdentifier("Segue1", sender: nil)
        case 1:
            self.performSegueWithIdentifier("Segue2", sender: nil)
        case 2:
            self.performSegueWithIdentifier("Segue3", sender: nil)
        default:
    }
}