2016-08-25 39 views
0

我在表格里面有custem单元格 里面我有一个按钮,我想当用户点击按钮时推送viewController,我该怎么做,以及如何知道该小区内的用户使用它的按钮,因为这里没有didSelectRowAtIndexPathcellView里面的按钮我无法知道用户按下了哪个单元格

+1

重复http://stackoverflow.com/questions/19000356/ios-7-how-to-get-the-indexpath-from-button-placed-in-uitableviewcell – JJBoursier

+0

@JJBoursier我希望在迅速,可以你为我解释一下吗?我不知道关于objective-c – joda

回答

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 

} 

从发送按钮的标签取indexPath和取细胞这个indexPath.Push您的导航控制器上的控制器

func transitonMethod(sender: AnyObject){ 
let indexPath = NSIndexPath.init(index: sender.tag) 
let cell = tableView.cellForRowAtIndexPath(indexPath) 

self.navigationController?.pushViewController(yourController, animated: true) 

}

0

声明一个IBAction为如下的建议在IOS 7 - How to get the indexPath from button placed in UITableViewCell

@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来执行任何您需要的操作。

+0

我在这个UItableViewCell类中写的,但我得到错误,它说“没有成员”tableView“ – joda

+0

你必须在包含TableView的ViewController中声明此方法... ... 1 - UIButton在你的单元格中,添加约束条件; 2 - 在包含TableView的ViewController中声明IBAction方法; 3 - 将按钮链接到单元格,并且你在单元格的控制器内部任意图形(如设置标题); 4发送事件到ViewController,你通过故事板声明了IBAction; – JJBoursier

+0

@JJBoursier你的第一个方法是不安全的,因为它依赖于tableViewCell的体系结构,它也是错误的,因为'sender.superview'不会让你细胞,它会让你到'tableViewCellContentView'。去你需要去两层的单元格,比如'(sender.superview)?superview' –

0

在的tableview的cellforRow方法:

1)设定按钮的标签例如yourButton.tag = indexpath.row

2)设置yourbutton egbuttonPressed的目标方法(发送者:在目标方法的UIButton)

3)现在,将得到indexpath.row通过sender.tag

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 
} 
+0

要访问'sender.indexPath'发件人应该是CustomButton类型。 –

+0

已编辑。谢谢@SamM – Manish

相关问题