【发布时间】:2019-07-18 11:58:27
【问题描述】:
我正在尝试在 tableview 单元格上实现动态按钮。我可以添加按钮,但根据最后一个单元格的要求,我不想添加按钮,但它也被添加到那里,如下面提到的屏幕截图
这是要求 我的 cellForRowAt indexPath 代码如下。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cell")
if let _ = cell {
print("cell is available")
} else {
cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
}
cell?.textLabel?.textAlignment = .left
cell?.textLabel?.text = list[indexPath.row]
let btn = UIButton(type: UIButtonType.custom) as UIButton
if cell?.textLabel?.text == "➕ Add Room" || list[indexPath.row] == "➕ Add Room"{
btn.isHidden = true
cell?.textLabel?.textAlignment = .center
}else{
btn.frame = CGRect(x: 146, y: 0, width: 20, height: (cell?.frame.height)!)
btn.addTarget(self, action: #selector(buttonPressed(sender: )), for: .touchUpInside)
btn.tag = indexPath.row
btn.setImage(UIImage(named: "delete.png"), for: .normal)
cellx = list[btn.tag]
cell?.contentView.addSubview(btn)
}
return cell!
}
此之后的结果显示在屏幕截图下方
我不想在表格最后一行的 +Add Room 行中显示删除按钮。 请建议我如何按照要求中提及的方式退出。我为文本(“添加房间文本”)设置了一个条件,使其显示在中心并成功显示在中心。 提前谢谢请帮我解决这个问题
第二期
在这个给定的列表中,如果我选择“COPENHAGEN”并尝试删除它,它删除上面的内容意味着 BARCELONA 文件被删除。我不会从列表中删除相同的选定内容。
【问题讨论】:
-
尝试在 if else 条件下添加断点,看看是否进入 if ?
-
这样写 if indexPath.row == (list.count - 1) { print("last row") // 在这里添加你的逻辑 }
-
每次单元格出列时,都会向您的单元格添加一个新按钮。你应该处理这个。
-
你只需要在else部分使用btn.isHidden = false
-
只需在 UITableViewCell 类中创建按钮而不是 cellForRowAtIndexPath 并根据 indexPath 隐藏和显示它,并且在 prepareForReuse 方法中使按钮隐藏。
标签: ios swift uitableview