我尝试了多种不同的方法来尝试制定一种方法来阻止我的按钮同时被多次勾选。在“selectButton”操作中,我正在寻找一种方法,为“checkLabel”UILabel 分配一个复选标记,并在点击另一个单元格时使相同的刻度消失(例如,我在其他地方点击“selectButton”)。 (请对我放轻松,我是编码新手😅)
这是我的 xib 文件:
class NewTableViewCell: UITableViewCell {
var doesContainTick = false
var count = 1
@IBOutlet var langaugeBox: UIView!
@IBOutlet var languageText: UILabel!
@IBOutlet var checkLabel: UILabel?
@IBAction func selectButton(_ sender: UIButton) {
if sender.isEnabled {
if count == 1 {
checkLabel?.text = "\u{02713}"
count = 2
} else {
checkLabel?.text = ""
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
我尝试使用不同的变量来创建一个计数系统(例如,如果“count”等于3,则删除勾号),但这不起作用(并且被删除了多次,尽管你可以看到我在上面再次尝试.)
构建表格视图时记住两点很有帮助。首先,单元格应始终反映底层数据源;您的单元格应该使视图控制器更新数据源,然后将其反映在单元格中,而不是尝试直接在单元格中改变状态。其次,滚动时会重复使用单元格,因此您不能依赖单元格滚动到屏幕外后的状态是否正确。
考虑到这一点,您应该更新
UITableView
的实际数据源,然后配置单元格以反映这一点,而不是尝试让一个单元格找出其他单元格的状态。如果适合您的设计,您还可以使用 UITableViewDelegate
didSelect
方法而不是创建自己的按钮。
这是一个例子
UITableViewController
:
struct SelectableCellViewModel {
let title: String
var isSelected: Bool
}
final class ViewController: UITableViewController {
private var cellData: [SelectableCellViewModel] = {
(0..<100).map { SelectableCellViewModel(title: "Option \($0)", isSelected: false) }
}()
private var selectedIndexPath: IndexPath?
override func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return cellData.count
}
override func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(
withIdentifier: "SelectableCell",
for: indexPath
) as! SelectableTableViewCell
let vm = cellData[indexPath.row]
cell.configure(with: vm)
return cell
}
override func tableView(_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath) {
//First deselect the cell. You set the selection style to .none
//in the xib to prevent any background flicker when the cell is
//tapped.
tableView.deselectRow(at: indexPath, animated: false)
//Update data source.
cellData[indexPath.row].isSelected = true
var indexPathsToReload = [indexPath]
if let selectedIndexPath {
//If anything is already selected, update its data source.
cellData[selectedIndexPath.row].isSelected = false
indexPathsToReload.append(selectedIndexPath)
}
//Reload the cells to reflect the new state of the data source
tableView.reloadRows(at: indexPathsToReload, with: .none)
selectedIndexPath = indexPath //Update selection state.
}
}
这是
UITableViewCell
:
class SelectableTableViewCell: UITableViewCell {
func configure(with viewModel: SelectableCellViewModel) {
var config = defaultContentConfiguration()
config.text = viewModel.title
contentConfiguration = config
accessoryType = viewModel.isSelected ? .checkmark : .none
}
}
您可以使用此过程的任何变体。例如,如果您的设计需要单元格上有一个实际按钮,请将视图控制器设置为单元格的委托,并让按钮调用更新数据源的委托方法。