首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >indexPath为零

indexPath为零
EN

Stack Overflow用户
提问于 2018-08-27 05:28:46
回答 2查看 189关注 0票数 0

我在一个表视图中有一个按钮和一个标签(我使用的是8行),由于某种原因,当我单击第一个按钮时,我得到了indexPath零错误,但是当我单击第二个按钮(第二行)时,我得到了第一行标签。当我点击第三行按钮时,我得到了第二行标签等等,为什么它们不对齐。我想当我点击第一行按钮得到第一行标签等。请参阅下面的代码。谢谢!!

代码语言:javascript
复制
   @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



}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-08-27 05:50:14

如果你别无选择的话,框架数学是最坏的情况。在这里你有很多选择。

例如,为什么不使用分配给按钮的tag

代码语言:javascript
复制
@objc func btnAction(_ sender: UIButton) {
    GlobalVariable.addedExercises.append(currentAnimalArray[sender.tag].name)
}

一个更快捷、更有效的解决方案是回调关闭:

TableCell中添加按钮操作和callback属性。不需要出口。断开插座并将按钮连接到Interface中的操作。当按钮被点击时,就会调用回调。

代码语言:javascript
复制
class TableCell: UITableViewCell {

    // @IBOutlet var b : UIButton!
    @IBOutlet var nameLbl : UILabel!

    var callback : (()->())?

    @IBAction func btnAction(_ sender: UIButton) {
        callback?()
    }
}

删除控制器中的按钮操作。

cellForRow中,为callback属性分配一个闭包

代码语言:javascript
复制
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对象是在闭包中捕获的。

票数 2
EN

Stack Overflow用户

发布于 2018-08-27 05:52:32

您已经传递了带有按钮标记的indexPath.row。简单地使用标记作为索引

代码语言:javascript
复制
@objc func btnAction(_ sender: UIButton) { 
    GlobalVariable.addedExercises.append(currentAnimalArray[sender.tag].name)
} 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52033010

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档