![](/img/trans.png)
[英]How do i disable/enable edit button when user doesn't fully swipe to delete table view cell?
[英]How do i enable a button only in the selected cell?
我有一个带有TableView的ViewController。 TableView是动态的,并且有一个带有Button的自定义单元格。 单元格的数量取决于api。
因此,每个单元格都包含一些从api传递的信息,每个单元格都有一个INFO按钮。 默认情况下,我设置
Btninfo.isUserInteractionEnabled = false
当用户点击一个单元格时
cell?.Btninfo.isUserInteractionEnabled = true
通过这种方法,将不会在用户选择单元格之前选择按钮,并且一旦用户选择了单元格,便会从该单元格获取信息,而使用单元格的indexPath.row获取其他一些细节。 然后,该“信息”按钮将打开一个弹出窗口,显示该单元格内部内容的详细信息。
现在的问题:
一旦用户选择了任何单元格,Btninfo将被启用,并将从该单元格中获取信息。 现在,如果用户单击另一个单元格中的“信息”按钮而不选择该单元格,则弹出窗口将显示从上一个单元格中获取的详细信息。
那么,如何仅对选定的单元格启用按钮,而对其他单元格禁用按钮? 并禁用该单元格中的按钮,并在下一个用户选择的单元格中启用它?
(我知道我可以禁用didDeselect上的单元格,而我不问这件事)
在自定义UITableViewCell
本身中进行处理。
要基于单元格选择启用/禁用Btninfo's
userInteraction,请重写UITableViewCell
setSelected(_:, animated:)
方法。
要禁用Btninfo's
userInteraction,当单元被重用时 ,请在prepareForReuse()
方法中将其禁用。
我的意思是说
class CustomCell: UITableViewCell {
@IBOutlet weak var Btninfo: UIButton!
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
self.Btninfo.isUserInteractionEnabled = selected
}
override func prepareForReuse() {
super.prepareForReuse()
self.Btninfo.isUserInteractionEnabled = false
}
}
setSelected(_:, animated:)
方法将在所有cells
自动处理Btninfo's
isUserInteractionEnabled
,即在所选cell
中将启用它,在其他cells
中将禁用它。 您无需在tableView(_:didSelectRowAt:)
方法中执行任何操作。
我现在在我的代码中使用类似的东西。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! Cell
cell.Btninfo.isUserInteractionEnabled = cell.isSelected
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? Cell {
cell.Btninfo.isUserInteractionEnabled = true
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? Cell {
cell.Btninfo.isUserInteractionEnabled = false
}
}
您已采用一组数组的模型类,如arrData: [Data] = []
在表视图中显示数据。
请在模型类中添加额外的变量,如isAbleToEnable = false
,用于显示该数据。 模型类如下:
Class Data {
….
{Your Content}
….
var isAbleToEnable = false
}
现在在tableview方法中,执行以下操作
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.arrData[indexPath.row].isAbleToEnable = true
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! Cell
If self.arrData[indexPath.row].isAbleToEnable {
cell.Btninfo.isUserInteractionEnabled = true
//do stuff
} else {
cell.Btninfo.isUserInteractionEnabled = false
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.