Reputation: 53
I have a button inside my tableview cell. How can I convert the following lines of code so that I will be performing the same functions when the button (instead of the row) is clicked? Thanks in advance.
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
// Get Cell Label
let indexPath = tableView.indexPathForSelectedRow!
let currentCell = tableView.cellForRowAtIndexPath(indexPath) as! PostCell
if currentCell.updateBtn.hidden == false {
valuetoPass = currentCell.favorTitle.text
valuetoPass_desc = currentCell.descriptionText.text
postKey = currentCell.post.postKey
performSegueWithIdentifier("seguetoVC", sender: self)
}
if currentCell.bidBtn.hidden == false {
bidInt = currentCell.post.bids
postKey = currentCell.post.postKey
passUsername = currentCell.post.username
performSegueWithIdentifier("seguetoBidVC", sender: self)
}
}
Upvotes: 1
Views: 714
Reputation: 283
Proper way is, create cell class and add action to cell class from xib. if button pressed then cell class method will be called and it will call delegate method that will be implemented by controller. e.g
protocol TableViewCellDelegate: NSObject {
func TableViewCell(cell: UITableViewCell, ButtonPressed sender: AnyObject)
}
class TableViewCell: UITableViewCell {
weak var delegate: CommentTableViewCellDelegate
}
IBACtion func sender() {
self.delegate.TableViewCell(self, ButtonPressed: sender)
}
In Controller, implement delegate of cell
func TableViewCell(cell: UITableViewCell, editButtonPressed sender: AnyObject) {
var indexPath: NSIndexPath = self.tableViewComments(forCell: cell)
}
Upvotes: 1
Reputation: 2924
You can add @selector
for cell button and assign row value as tag for each row. And when you tap on any cell button you can called method which you added in @selector
and by button tag, you can get index for that cell.
For Example: In cell for row function:
[cell.btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
cell.btn.tag = indexPth.row;
And Function:
-(void) btnClick:(UIButton *) btn {
NSIndexPath *path = [NSIndexPath indexPathForRow:btn.row inSection:0];
}
Thanks
Upvotes: 0
Reputation: 625
Use Closures for taping events in cells it's soo easy than delegates.
Upvotes: 0
Reputation: 24341
You can use block for doing this. While creating the cell set the block in cellForRowAtIndexPath. Then call this block whenever the button is tapped in button's IBAction method.
Upvotes: 0