I have a tableview controller that displays a row of cells. Each cell has 3 buttons. I have numbered the tags for each cell to be 1,2,3. The problem is I don't know how to find on which cell a button is being pressed. I'm currently only getting the sender's tag when one of the buttons has been pressed. Is there a way to get the cell row number as well when a button is pressed?
相关问题
- CALayer - backgroundColor flipped?
- Core Data lightweight migration crashes after App
- How can I implement password recovery in an iPhone
- State preservation and restoration strategies with
- “Zero out” sensitive String data in Swift
相关文章
- 现在使用swift开发ios应用好还是swift?
- UITableView dragging distance with UIRefreshContro
- TCC __TCCAccessRequest_block_invoke
- Where does a host app handle NSExtensionContext#co
- xcode 4 garbage collection removed?
- Unable to process app at this time due to a genera
- Swift - hide pickerView after value selected
- How can I add media attachments to my push notific
You should really be using this method instead:
Swift version:
That will give you the
indexPath
based on the position of the button that was pressed. Then you'd just callcellForRowAtIndexPath
if you need the cell orindexPath.row
if you need the row number.If you're paranoid, you can check for
if (indexPath) ...
before using it just in case theindexPath
isn't found for that point on the table view.All of the other answers are likely to break if Apple decides to change the view structure.
I would recommend this way to fetch indexPath of cell which has any custom subview - (compatible with iOS 7 as well as all previous versions)
This doesn't require
self.tablview
either.Also, notice the commented code which is useful if you want the same through a @selector of UIGestureRecognizer added to your custom subview.
Swift 3
Note: This should really go in the accepted answer above, except that meta frowns upon such edits.
Two minor comments:
I would like to share code in swift -
One solution could be to check the tag of the button's superview or even higher in the view hierarchy (if the button is in the cell's content view).
There are two ways:
@H2CO3 is right. You can do what @user523234 suggested, but with a small change, to respect the UITableViewCellContentView that should come in between the UIButton and the UITableViewCell. So to modify his code:
If you create a custom UITableViewCell (your own subclass), then you can simply call
self
in the IBAction. You can link the IBAction function to your button by using storyboard or programmatically when you set up the cell.