如何解决如果在tableView swift中取消选择项目,如何删除数组中的项目
如果我在tableView中取消选择一个项目,它不会从Array中删除。当我选择一个项目时,它可以正常工作,但是如果我想取消选择,我不知道如何编码。我的问题是如何从阵列中删除此项。 这是tableView代码:
var highlightsArray: [String] = []
var highlightRow: String = ""
func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
return highlightsArray.count
}
func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "com.nils.PrototypeCellHighlights",for: indexPath) as? CheckableTableViewCell
let highlights = highlightsArray[indexPath.row].components(separatedBy: "," )
cell?.textLabel?.text = highlights.first
return cell!
}
func tableView(_ tableView: UITableView,didSelectRowAt indexPath: IndexPath) {
if tableView == highlightTableView {
highlightRow = highlightsArray[indexPath.row]
let selected_indexPaths = tableView.indexPathsForSelectedRows
for indexPath in selected_indexPaths! {
let highlightName = tableView.cellForRow(at: indexPath)
let highlightText = (highlightName?.textLabel?.text)!
if highlightValue.contains(highlightText) {
}
else {
highlightValue.append((highlightName?.textLabel?.text)!)
}
}
}
}
func tableView(_ tableView: UITableView,didDeselectRowAt indexPath: IndexPath) {
}
此外,我还有一个用于tableView单元格的类:
class CheckableTableViewCell: UITableViewCell {
override init(style: UITableViewCell.CellStyle,reuseIdentifier: String?) {
super.init(style: style,reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func setSelected(_ selected: Bool,animated: Bool) {
super.setSelected(selected,animated: animated)
self.accessoryType = selected ? .checkmark : .none
}
}
至少这是完成按钮:
@objc func doneButton() {
if highlightValue == [] {
let alert = UIAlertController(title: "Error",message: "You didn't select anything",preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK",style: .cancel,handler: nil))
self.present(alert,animated: true)
}
print(highlightValue)
highlightValue = []
}
如果您有任何疑问,请告诉我
解决方法
取消选择行时是否要从数组中删除项目? 试试
didDeselectRowAt{
highlightValue.remove(at:indexpath.row)
table.reloadData()
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。