当我加载我的应用程序时,我看到所有单元格都有一个选中标记。我希望它不被选中。
有人从下面的代码中知道为什么会这样吗? (这是视图控制器中唯一带有选中标记附件的部分。)
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView.cellForRow(at: indexPath)?.accessoryType == .checkmark {
tableView.cellForRow(at: indexPath)?.accessoryType = .none
} else {
tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
}
}
答案 0 :(得分:0)
请参见下面的代码。您需要在“行”的单元格中设置默认的附件类型,然后在didSelectRow上可以根据逻辑进行更改。我创建了一个简单的模型,展示了如何在重新加载时设置默认的附件类型
import UIKit
struct CellInfo{
var title:String
var isSelected:Bool
}
class MyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var myTV: UITableView!
var CellInfoArr = [
CellInfo(title: "First Row", isSelected: false),
CellInfo(title: "Second Row", isSelected: false),
CellInfo(title: "Third Row", isSelected: false),
CellInfo(title: "Fourth Row", isSelected: false),
CellInfo(title: "Fifth Row", isSelected: false)
]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
myTV.delegate = self
myTV.dataSource = self
myTV.reloadData()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return CellInfoArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = CellInfoArr[indexPath.row].title
if CellInfoArr[indexPath.row].isSelected == true{
cell.accessoryType = .checkmark
}else{
cell.accessoryType = .none
}
cell.selectionStyle = .none
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
if tableView.cellForRow(at: indexPath)?.accessoryType == .checkmark {
tableView.cellForRow(at: indexPath)?.accessoryType = .none
CellInfoArr[indexPath.row].isSelected = false
} else {
tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
CellInfoArr[indexPath.row].isSelected = true
}
}
}