我在tableView中有自定义单元格
在它里面我有一个按钮,我希望当用户点击按钮按下viewController时,我该怎么做以及如何知道哪个单元格用户使用它的按钮,因为这里不是didSelectRowAtIndexPath
答案 0 :(得分:2)
创建自定义按钮类
class CustomButton: UIButton {
var indexPath: NSIndexPath!
}
在自定义单元格中,创建CustomButton类型的按钮,在cellForRowAtIndexPath
cell.yourCustomButton.indexPath = indexPath
像这样定义IBAction
@IBAction func customButtonClicked(sender: CustomButton) {
let indexPath: NSIndexPath = sender.indexPath
// Do whatever you want with the indexPath
}
答案 1 :(得分:0)
按照IOS 7 - How to get the indexPath from button placed in UITableViewCell:
中的建议声明IBAction如下@IBAction func didTapOnButton(sender: UIButton) {
let cell: UITableViewCell = sender.superview as! UITableViewCell
let indexPath: NSIndexPath = self.tableView.indexPathForCell(cell)
// Do anything with the indexPath
}
或其他方法:
@IBAction func didTapOnButton(sender: UIButton) {
let center: CGPoint = sender.center
let rootViewPoint: CGPoint = sender.superview?.convertPoint(center, toView: tableView)
let indexPath: NSIndexPath = tableView.indexPathForRowAtPoint(rootViewPoint!)
print(indexPath)
}
然后使用indexPath来做你需要的任何事情。
答案 2 :(得分:0)
在tableview的cellforRow方法中:
1)设置按钮的标签,例如yourButton.tag = indexpath.row
2)设置你的按钮的目标方法,例如按钮(发送者:UIButton)
3)现在,在目标方法中,您将获得sender.tag
的indexpath.row答案 3 :(得分:0)
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier) as! CustomCell
cell.button.tag = indexPath.row
cell.button.addTarget(self, action: #selector( self.transitonMethod ), forControlEvents: UIControlEvents.TouchUpInside)
return cell
}
func transitonMethod(sender: AnyObject){
let indexPath = NSIndexPath.init(index: sender.tag)
let cell = tableView.cellForRowAtIndexPath(indexPath)
self.navigationController?.pushViewController(yourController, animated: true)
}