我在一个表视图中有一个按钮和一个标签(我使用的是8行),由于某种原因,当我单击第一个按钮时,我得到了indexPath零错误,但是当我单击第二个按钮(第二行)时,我得到了第一行标签。当我点击第三行按钮时,我得到了第二行标签等等,为什么它们不对齐。我想当我点击第一行按钮得到第一行标签等。请参阅下面的代码。谢谢!!
@objc func btnAction(_ sender: AnyObject) {
var position: CGPoint = sender.convert(.zero, to: self.table)
print (position)
let indexPath = self.table.indexPathForRow(at: position)
print (indexPath?.row)
let cell: UITableViewCell = table.cellForRow(at: indexPath!)! as
UITableViewCell
print (indexPath?.row)
print (currentAnimalArray[(indexPath?.row)!].name)
GlobalVariable.addedExercises.append(currentAnimalArray[(indexPath?.row)!].name)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as? TableCell else {return UITableViewCell() }
// print(indexPath)
cell.nameLbl.text=currentAnimalArray[indexPath.row].name
// print("\(#function) --- section = \(indexPath.section), row = \(indexPath.row)")
// print (currentAnimalArray[indexPath.row].name)
cell.b.tag = indexPath.row
// print (indexPath.row)
cell.b.addTarget(self, action: #selector(SecondVC.btnAction(_:)), for: .touchUpInside)
return cell
}发布于 2018-08-27 05:50:14
如果你别无选择的话,框架数学是最坏的情况。在这里你有很多选择。
例如,为什么不使用分配给按钮的tag?
@objc func btnAction(_ sender: UIButton) {
GlobalVariable.addedExercises.append(currentAnimalArray[sender.tag].name)
}一个更快捷、更有效的解决方案是回调关闭:
在TableCell中添加按钮操作和callback属性。不需要出口。断开插座并将按钮连接到Interface中的操作。当按钮被点击时,就会调用回调。
class TableCell: UITableViewCell {
// @IBOutlet var b : UIButton!
@IBOutlet var nameLbl : UILabel!
var callback : (()->())?
@IBAction func btnAction(_ sender: UIButton) {
callback?()
}
}删除控制器中的按钮操作。
在cellForRow中,为callback属性分配一个闭包
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// no guard, the code must not crash. If it does you made a design mistake
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! TableCell
let animal = currentAnimalArray[indexPath.row]
cell.nameLbl.text = animal.name
cell.callback = {
GlobalVariable.addedExercises.append(animal.name)
}
return cell
}您可以看到,根本不需要索引路径。animal对象是在闭包中捕获的。
发布于 2018-08-27 05:52:32
您已经传递了带有按钮标记的indexPath.row。简单地使用标记作为索引
@objc func btnAction(_ sender: UIButton) {
GlobalVariable.addedExercises.append(currentAnimalArray[sender.tag].name)
} https://stackoverflow.com/questions/52033010
复制相似问题