我有一个自定义的UITableViewCell,我使用Interface Builder连接了我的UIButton
@IBOutlet var myButton: UIButton!
在UITableViewController的单元格配置下,我有以下代码:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var customCell = tableView.dequeueReusableCell(withIdentifier: self.MY_CELL_IDENTIFIER, for: indexPath) as! myCustomCell
// CONFIGURE OTHER CELL PARAMETERS
customCell.myButton.tag = indexPath.row
customCell.myButton.addTarget(self, action: #selector(myButtonPressed), for: UIControlEvents.touchUpInside)
return customCell
}
最后,我有
private func myButtonPressed(sender: UIButton!) {
let row = sender.tag
print("Button Sender row: \(row)")
}
此代码不起作用,除非我将函数定义更改为:
@objc private func myButtonPressed(sender: UIButton!) {
let row = sender.tag
print("Button Sender row: \(row)")
}
在Swift 3中有更好的方法在自定义UITableViewCell上实现UIButton
答案 0 :(得分:6)
我不是使用查看#store csv file as variable and take first column
$CSVList = (import-csv "c:\temp\missing.csv" -Header col1).col1
#delete if word matches .csv entry
$targetdirectory = "C:\temp2"
$Files = Get-childItem $targetdirectory -Recurse | Where-Object {$CSVList -contains $_.BaseName } | remove-item -whatif
write-host $Files
的忠实粉丝。取而代之的是,您可以使用tag
的委托模式在按钮被点击时收到通知。
viewController
答案 1 :(得分:1)
是的,有一个更聪明,更好的方法来做到这一点。您的方法的主要问题是它只有在没有插入,删除或移动单元格操作时才有效。因为这些操作中的任何一个都可以更改为不同indexPath创建的单元格的de indexPath。
我使用的系统是:
1.-在你的单元类MyCustomCell中创建一个IBAction(使用大写字母M.这是一个类,所以正确命名)。
2.-将按钮连接到该操作。
3.-使用至少一个方法
声明协议MyCustomCellDelegatefunc myCustomCellButtonAction(_ cell:MyCustomCell)
并向MyCustomCell添加属性
var delegate : MyCustomCellDelegate?
4.-将视图控制器设置为MyCustomCellDelegate
在连接到按钮的MyCustomCell方法中调用委托方法:
delegate?.myCustomCellButtonAction( self )
5.-在视图控制器中,方法cellForRowAt:
customCell.delegate = self
6.-在视图控制器中,方法myCustomCellButtonAction:
func myCustomCellButtonAction( _ cell: MyCustomCell ) {
let indexPath = self.tableView.indexPathForCell( cell )
// ...... continue .....
}
答案 2 :(得分:0)
您也可以使用委托来执行相同操作。
直接在自定义UITableViewCell类中映射按钮的IBAction。
在viewcontroller中实现委托方法,在按钮操作中从自定义单元格调用委托方法。