【发布时间】:2017-07-10 14:48:11
【问题描述】:
我正在尝试解决当表格视图“自上而下”时如何在 UITableViewCell 中操作按钮 - 例如,每个新行都添加到表格视图的顶部。我通过以下代码实现了这一点:
我使用以下代码将新项目插入到我的模型数组中,然后插入到 tableview 中:
let newItem = Item(text: inputTextView.text, time: Date())
items.insert(newItem, at: 0) //inserting into the front of model array
tableView.beginUpdates()
let indexPath:IndexPath = IndexPath(row:0, section:0)
tableView.insertRows(at: [indexPath], with: .fade)
tableView.endUpdates()
在 cellForRowAt 函数中,我运行以下代码:
let cell = tableView.dequeueReusableCell(withIdentifier: postCellID, for: indexPath) as! NewPostCell
let item = items[indexPath.row]
cell.postTextLabel.text = text
cell.timeLabel.text = dateFormatter.string(from: time)
cell.selectionStyle = .none
return cell
我的每个 tableview 单元格中都有三个按钮。
如何连接这些按钮,以便知道从哪个 indexPath 按下了哪个按钮?
问题是,如果我使用 indexPath.row 来标记按钮,那么所有单元格中的按钮都会被标记为 0,因为每个插入都发生在 indexPath.row 第 0 位的表格顶部。
我想用我的模型数组的当前大小来标记按钮,但这也不起作用,因为当重新使用单元格时,它们可以在那时用数组的长度进行标记,这将是错了。
有很多应用程序在表格视图类型的设置中具有“顶部的最后一个条目”,并且在单元格中带有按钮。所以一定有办法做到这一点。
【问题讨论】:
-
除了其他答案之外,您还可以使用委托传递单元格,然后将单元格的位置转换为 indexPath。这样就不需要标签
标签: ios swift uitableview swift3