ios - 如何在点击另一个单元格后操作 UITableViewCell? - swift

标签 ios swift uitableview

如何在点击另一个单元格后操作 UITableViewCell

我有 3 个单元格,每个单元格都有 UIPickerView 第一个单元格的 userInteractionEnabledtrue 但第二个和第三个是 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/

相关文章:

swift - 在 Swift Web View 中打开 Skype

ios - TableView 单元格中的 UIGestureRecognizer 获取 indexPath 始终返回最后一个单元格的 indexPath

iphone - 是否可以从 Nib 的代码中访问 UITableView 的 ScrollView?

iphone - UITableView 和 numberOfRowsInSection 崩溃

ios - 在设备 iphone ios sdk 上调试具有 2 个版本的同一项目?

ios - json 解析期间的控制流程 - Objective C

ios - 基于iOS版本的条件单元测试

ios - 在 iOS 游戏应用程序和 Swift 中使用 AdMob 插页式广告

Swift: '!=' 不能应用于类型为 'String' 和 'Any' 的操作数

ios - 是否需要请求 Siri 授权?