Kev*_*vin 2 uitableview ios swift
我在tableview单元格上设置了一个按钮,我想知道如何操作它.也就是说,我有兴趣更改按钮的名称标题,并在单击按钮时添加另一个目标(按钮的不同功能).我的想法是需要将它添加到buttonClicked func中,但我不确定如何引用被单击的特定cellForRow.或许可以在cellForRow中使用条件来确定按钮标题是什么?我不太清楚最好的办法是什么.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = guestTableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let button : UIButton = UIButton(type:UIButtonType.custom) as UIButton
button.frame = CGRect(origin: CGPoint(x: 200,y :60), size: CGSize(width: 100, height: 24))
let cellHeight: CGFloat = 44.0
button.center = CGPoint(x: view.bounds.width / (4/3), y: cellHeight / 2.0)
button.setTitleColor(.blue, for: .normal)
button.addTarget(self, action: #selector(buttonClicked), for: UIControlEvents.touchUpInside)
button.setTitle("Add", for: UIControlState.normal)
cell.addSubview(button)
return cell
}
func buttonClicked(sender : UIButton!) {
print("Added!")
}
Run Code Online (Sandbox Code Playgroud)
对于Swift 3.2和4.0
找到" indexPath.row"和" indexPath.section"
//在"cellForRowAt"按钮上添加目标
cell.myBtn.addTarget(self, action: #selector(self.btnAction(_:)), for: .touchUpInside)
Run Code Online (Sandbox Code Playgroud)
//添加功能
func btnAction(_ sender: UIButton) {
let point = sender.convert(CGPoint.zero, to: yourTableView as UIView)
let indexPath: IndexPath! = yourTableView.indexPathForRow(at: point)
print("row is = \(indexPath.row) && section is = \(indexPath.section)")
}
Run Code Online (Sandbox Code Playgroud)
更改和添加您的代码
button.addTarget(self, action:#selector(YourViewController.buttonClicked(_:)), for: .touchUpInside)
button.tag = indexPath.row
func buttonClicked(sender : UIButton!) {
print("Added!")
let row = sender.tag;
print(row)
}
Run Code Online (Sandbox Code Playgroud)