我在TableViewController中有一个静态表。每当我选择一行时,它会用灰色填充整个单元格。它为我点击的每一行都这样做。如果我使用:
cell.selectionStyle = .none
它会使细胞填充白色。
Tableview属性检查器:
TableViewCell属性检查器:
TableViewController:
import UIKit
class OptionTableViewController: UITableViewController {
@IBOutlet var optionsTable: UITableView!
let defaults = UserDefaults.standard
let numberOfRows = [7,2]
let cellIdentifier = "OptionCells"
override func viewDidLoad() {
super.viewDidLoad()
optionsTable.register(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that con be recreated.
}
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
var rows = 0
if(section < numberOfRows.count){
rows = numberOfRows[section]
}
return rows
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.selectionStyle = .none
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
cell.textLabel?.text = optionSelections[indexPath.row]
return cell
}
}
我相信我已经正确设置了所有内容。当我点击它们时为什么要填充单元格?
更新 我更新了代码以显示我目前拥有的内容。
更新2: 我已经包含了几张图片,以显示在敲击其他每个单元格之前和之后表格的样子。
更新3: 我正在将单元格出列以将附件类型更改为复选标记。
答案 0 :(得分:1)
您需要在选择发生之前设置selectionStyle。
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.selectionStyle = .none
cell.selectedBackgroundView = UIView() // optional
cell.selectedBackgroundView?.backgroundColor = UIColor.white // optional
}
答案 1 :(得分:1)
正如评论中所讨论的,我认为这个问题是didSelectRow(at:)
方法中出现单元格出现的症状:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
}
您应该使用
let cell = tableView.cellForRow(at: indexPath)
获取当前位于给定indexPath的单元格(请注意,如果该indexPath已滚动关闭或从未在屏幕上显示,则它可能返回nil)。 Dequeuing获取一个未使用的单元格来到达给定的indexPath - 然后(我认为)然后位于现有单元格的前面 - 因此这是一种奇怪的行为。