我有一个表格视图,里面装有4行。
第3行将有一个复选框。我想仅在选中Row3复选框时启用第4行
所以我有一个复选框的插座(这是按钮)和动作点击该复选框。
我的问题是如何引用下一个单元格并使其启用/禁用
我试图将该单元格的引用作为myTableView.cellForRow(at: index + 1)
,但它抛出错误,二进制操作数无法应用于indexPath。
请建议我如何实现
点击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
我假设你有自己的自定义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的数据源。东西的个数。
在该checkBox的操作中,您可以执行tableview的reloadData
。之后,您可以在cellForRowAtIndexPath
内查看
喜欢:
if indexpath.row == 4
then
//just my opinion, you can do whatever you want.
cell.userInteractionEnabled = checkBox.isSelected
或者你可以在numberOfRowsInSection
里面查看,你可以从dataSource中删除它。
我会建议优化和稳健的方式。
如果你有和Datasource Array
加载TableView
然后在对象中添加一个名为isEnabled的额外属性。
其他
创建一个Array
如下
var cellStateArray = Array(repeating: true, count: numberOfRows)
然后当你打开复选框时,根据那个切换所需单元格索引的标志(当前它是你的第4行)到false
或true
中的cellStateArray
在cellForRowAt
方法中,检查cellStateArray
中相应cell index
的标志,并设置userInteractionEnabled启用/禁用(如果需要,可以进行额外配置)
然后简单地重新加载单元格/表格