如何在点击另一个单元格后操作 UITableViewCell
?
我有 3 个单元格,每个单元格都有 UIPickerView
第一个单元格的 userInteractionEnabled
是 true
但第二个和第三个是 false
.. 当用户点击第一个单元格时,其余单元格的 userInteractionEnabled
应该是 true
我知道我需要使用 userInteractionEnabled
但如何使用?我应该将细胞保存在变量中然后在需要时进行操作吗?
最佳答案
我已经阅读了上面的解决方案并且当然都是有效的,但我更喜欢这样的解决方案:我想你有一个对象数组要显示(忽略你正在使用的模式)。
class MyObject: NSObject {
var selected: Bool = false
}
class MyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var objects: [MyObject] = []
override func viewDidLoad() {
super.viewDidLoad()
// init your objects:
// 1stObj.enabled = true
// 2ndObj.enabled = false
// 3rdObj.enabled = false
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let obj = self.objects[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.userInteractionEnabled = obj.enabled
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
for obj in self.objects {
obj.selected = !obj.selected
}
tableView.deselectRowAtIndexPath(indexPath, animated: true)
tableView.reloadData()
}
}
我认为此解决方案更具可扩展性和可维护性,但这是我的看法。
更新
要在'cellForRowAtIndexPath' 函数之外操作单元格,您可以这样做,例如:
func manuallyModifyCell(atIndex index: Int, backgroundColor: UIColor = .clearColor()) {
let indexPath = NSIndexPath(forRow: index, inSection: 0)
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
cell.backgroundColor = backgroundColor
}
}
关于ios - 如何在点击另一个单元格后操作 UITableViewCell? - swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39117431/