Я поискал в Интернете свою проблему, но в моем случае ничего не помогло. Это что-то особенное.
В моем приложении есть функция контрольного списка, все работает нормально, но есть эта проблема. При добавлении checkmark
в UITableViewCell
и удалении одной из других ячеек после этого. Все checkmarks
будут удалены.
Я думал, что у массива и соединения возникают проблемы, когда что-то удаляется. Я имею в виду «порядок» свойств в массиве. Я попросил своих коллег (ИТ), но никто не смог мне помочь.
class ViewControllerChecklist: UIViewController, UITableViewDelegate, UITableViewDataSource{
@IBOutlet weak var myTableView: UITableView!
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (checklist.count)
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
cell.textLabel?.textColor = UIColor(red: 4 / 255.0, green: 59 / 255.0, blue: 101 / 255.0, alpha: 1.0)
cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 18.0)
cell.textLabel?.text = checklist[indexPath.row]
return cell
}
// checkmarks when tapped
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
tableView.deselectRow(at: indexPath, animated: true)
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCellEditingStyle.delete {
checklist.remove(at: indexPath.row)
myTableView.reloadData()
}
}
override func viewDidAppear(_ animated: Bool) {
myTableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
UITableViewCell.appearance().tintColor = UIColor(red: 237 / 255.0, green: 108 / 255.0, blue: 4 / 255.0, alpha: 1.0)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
2 ответа
Вы можете попробовать этот код.
Сохраните выбранное значение и сравните во время UITableView
reloadData ().
class ViewControllerChecklist: UIViewController, UITableViewDelegate, UITableViewDataSource{
@IBOutlet weak var myTableView: UITableView!
var selectedChecklist: [String] = []
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (checklist.count)
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
cell.textLabel?.textColor = UIColor(red: 4 / 255.0, green: 59 / 255.0, blue: 101 / 255.0, alpha: 1.0)
cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 18.0)
cell.textLabel?.text = checklist[indexPath.row]
if selectedChecklist.contains(checklist[indexPath.row]) {
cell.accessoryType = .checkmark
}
else{
cell.accessoryType = .none
}
return cell
}
// checkmarks when tapped
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
selectedChecklist.append(checklist[indexPath.row])
tableView.deselectRow(at: indexPath, animated: true)
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let value = checklist.remove(at: indexPath.row)
myTableView.reloadData()
}
}
override func viewDidAppear(_ animated: Bool) {
myTableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
UITableViewCell.appearance().tintColor = UIColor(red: 237 / 255.0, green: 108 / 255.0, blue: 4 / 255.0, alpha: 1.0)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Более простое решение - сделать так, чтобы ваш список объектов контрольного списка добавлял isChecked
в ваш контрольный список.
struct Object {
var tag:String
var isChecked:Bool
}
И составьте такой список:
var checkList = [Object]()
Наконец, в функции cellForRowAt:
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// rest of code goes here...
if checklist[indexPath.row].isChecked {
cell.accessoryType = .checkmark
}
else{
cell.accessoryType = .none
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
checkList[indexPath.row].isChecked = true
tableView.deselectRow(at: indexPath, animated: true)
}
Похожие вопросы
Новые вопросы
arrays
Массив - это упорядоченная линейная структура данных, состоящая из набора элементов (значений, переменных или ссылок), каждый из которых идентифицируется одним или несколькими индексами. Когда вы спрашиваете о конкретных вариантах массивов, используйте вместо них следующие связанные теги: [vector], [arraylist], [matrix]. При использовании этого тега в вопросе, относящемся к языку программирования, пометьте вопрос используемым языком программирования.