添加变量
var buttonPars:[Int:IndexPath] = [:];
最常用的方式是直接给button设置tag
cell.actionButton.addTarget(self, action: #selector(actionButtonClick(button:)), for: UIControlEvents.touchUpInside)
let tagNum = indexPath.section*1000000 + indexPath.row;
cell.actionButton.tag = tagNum;
self.buttonPars[tagNum] = indexPath;
点击事件
@objc func actionButtonClick(button:UIButton){
print("button.tag:\(button.tag)");
if let indexPath = self.buttonPars[button.tag]{
print("section:\(indexPath.section)");
print("row:\(indexPath.row)");
}
}
iOS牛掰在可以修改运行时 可以直接绑定两个对象 具体代码如下
class SonghuoViewController: UIViewController{
//定义静态变量
static var action = "action";
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("songhuoCell", forIndexPath: indexPath) as! SonghuoTableViewCell;
cell.actionButton.addTarget(self, action: #selector(actionButtonClick(button:)), forControlEvents: UIControlEvents.TouchUpInside);
//创建关联
objc_setAssociatedObject(cell.actionButton, &SonghuoViewController.action, indexPath, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC);
return cell;
}
@objc func actionButtonClick(button:UIButton){
//获取关联的对象
if let indexPath = objc_getAssociatedObject(button, &SonghuoViewController.action) as? NSIndexPath{
print("section:\(indexPath.section)");
print("row:\(indexPath.row)");
}
}
}
objc_setAssociatedObject(cell.actionButton, &SonghuoViewController.action, indexPath, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC);
该函数需要四个参数:源对象,关键字,关联的对象和一个关联策略
objc_getAssociatedObject(button, &SonghuoViewController.action)
该函数需要两个参数:源对象,关键字
传入nil即可
objc_setAssociatedObject(cell.actionButton, &SonghuoViewController.action, nil, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC);