Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing accessoryButtonTappedForRowWithIndexPath: in Swift 2

I'm attempting to implement accessoryButtonTappedForRowWithIndexPath: in Swift 2 on a UITableViewController.

As I explain below, I think I'm missing something in when I create the disclosureIndicator, but I don't know what. It gets drawn from code, but my target action doesn't get called. UGH!

To do this programmatically, my understanding is I need to add the detailDisclosure indicator in cellForRowAtIndexPath before my cell is returned. I'm doing that as follows:

// Create disclosure indicator button in the cell
let disclosureIndicatorButton = UIButton(type: UIButtonType.DetailDisclosure)
disclosureIndicatorButton.addTarget(self, action: "disclosureIndicatorPressed:event:", forControlEvents: UIControlEvents.TouchUpInside)
customCell.accessoryType = .DisclosureIndicator

In my code, the detailDisclosure chevron gets drawn, but the target action method I assigned to it doesn't get called.

Then I need to create a handler for the button when it's pressed:

func disclosureIndicatorPressed(sender: UIButton, event: UIControlEvents) {
    print("disclosure button pressed")
    // convert touches to CGPoint, then determine indexPath
    // if indexPath != nil, then call accessoryButtonTappedForRowWithIndexPath
}

Finally accessoryButtonTappedForRowWithIndexPath contains code to perform the segue, which I can do. What am I missing?

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableViewDelegate_Protocol/#//apple_ref/occ/intfm/UITableViewDelegate/tableView:accessoryButtonTappedForRowWithIndexPath:

like image 964
Adrian Avatar asked Oct 18 '15 13:10

Adrian


1 Answers

Not sure why you are adding disclosure button indicator like that in code.

What you are looking for is simply 2 step process -

Step 1 : Add correct accessoryType on cell:

cell.accessoryType = .DetailDisclosureButton

Step 2 : Take action when the button is tapped by creating the accessoryButtonTappedForRowWithIndexPath function:

override func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath) {
    doSomethingWithItem(indexPath.row)
}
like image 54
Abhinav Avatar answered Sep 30 '22 18:09

Abhinav