在表格视图单元内单击按钮时执行功能
问题描述:
我的桌面视图单元格内有一个按钮。如何转换以下代码行,以便在点击按钮(而不是行)时执行相同的功能?提前致谢。在表格视图单元内单击按钮时执行功能
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)
}
}
答
您可以为细胞按钮添加@selector
并指定行值作为标记的每一行。当你点击任何单元格按钮时,你可以调用你在@selector
中添加的方法和按钮标签,你可以获得该单元格的索引。
例如:在为行功能细胞:
[cell.btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
cell.btn.tag = indexPth.row;
及功能:
-(void) btnClick:(UIButton *) btn {
NSIndexPath *path = [NSIndexPath indexPathForRow:btn.row inSection:0];
}
感谢
答
您可以使用块这样做。在创建单元格时,在cellForRowAtIndexPath中设置该块。然后在按钮的IBAction方法中点击按钮时调用此块。
答
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)
}
u能放的cellForRowAtIndexPath的代码? –