启用/禁用表格视图单元格 - iOS - Swift

问题描述 投票:1回答:4

我有一个表格视图,里面装有4行。

第3行将有一个复选框。我想仅在选中Row3复选框时启用第4行

所以我有一个复选框的插座(这是按钮)和动作点击该复选框。

我的问题是如何引用下一个单元格并使其启用/禁用

我试图将该单元格的引用作为myTableView.cellForRow(at: index + 1),但它抛出错误,二进制操作数无法应用于indexPath。

请建议我如何实现

ios swift uitableview
4个回答
0
投票

点击checkBox,假设有一个方法名称checkBoxClicked。你可以这样做:

@IBAction func checkBoxClicked(_ sender: Any) {
        let button = sender as! UIButton
        let clickedIndex = button.tag

        let nextIndexPath = IndexPath(item: clickedIndex+1, section: 0) // specify section here, if it's sectioned tableview
        let cell = tableView.cellForRow(at: nextIndexPath)

        // enable cell here
        cell?.isUserInteractionEnabled = true    // or reload cell
}

不要忘记将标记设置为cellForRowAtIndexPath方法中的复选框,如:

cell.checkBoxButton.tag = indexPath.row

1
投票

我假设你有自己的自定义UITableViewCell类。而你的MyTableViewController是这个tableview单元的代表。每当用户选中/取消选中时,您的盒子委托会告诉您的控制器,并且您调用重载方法来摆脱给定的行。

这是我在我的应用程序中使用的解决方案。

import Foundation
import UIKit

class MyTableViewController: UITableViewController {
    private struct CurrentSetting {
        var RowAEnabled: Bool = true
        var RowBEnabled: Bool = true
        var RowCEnabled: Bool = true
        var RowDEnabled: Bool = true
        var RowEEnabled: Bool = true
        //...
        //maybe more?
    }


    /// Let's say those are your table view rows. Data or whatever.
    fileprivate var settings: [String] {
        //In here you have your static position.
        var configuration = ["Row A","Row B", "Row C"]
        //However, if some data are enabled/disabled you modify it based on settings
        if current.RowAEnabled {
            configuration += ["Row D"]
        }
        return configuration
    }
    //This is your setting for current tableview
    private var current = CurrentSetting()
}

//Use this to reload row for your enable/disable cell.
tableView.reloadRows(at: [indexPath], with: .none)

示例如何使用我的应用程序。重要信息:设置它是tableview的数据源。东西的个数。

enter image description here


0
投票

在该checkBox的操作中,您可以执行tableview的reloadData。之后,您可以在cellForRowAtIndexPath内查看

喜欢:

if indexpath.row == 4  
then  
//just my opinion, you can do whatever you want.  
cell.userInteractionEnabled = checkBox.isSelected 

或者你可以在numberOfRowsInSection里面查看,你可以从dataSource中删除它。


0
投票

我会建议优化和稳健的方式。

如果你有和Datasource Array加载TableView然后在对象中添加一个名为isEnabled的额外属性。

其他

创建一个Array如下

var cellStateArray = Array(repeating: true, count: numberOfRows)

然后当你打开复选框时,根据那个切换所需单元格索引的标志(当前它是你的第4行)到falsetrue中的cellStateArray

cellForRowAt方法中,检查cellStateArray中相应cell index的标志,并设置userInteractionEnabled启用/禁用(如果需要,可以进行额外配置)

然后简单地重新加载单元格/表格

© www.soinside.com 2019 - 2024. All rights reserved.