我正在使用 tableview 進行多行選擇,并使用按鈕進行復選。使用此代碼能夠添??加所有選定的行 idarrSelectedRows并且能夠在取消選擇時洗掉....但是在這里我添加了所有選定的行 JSON 標題arrSubCat并且無法洗掉
代碼:在此代碼arrSubCat中是字串陣列..在此陣列中,我正在添加選定的行 JSON 標題..這里的問題是,如果我取消選擇該行,則無法從arrSubCat陣列中洗掉取消選擇的行標題
如果我這樣嘗試arrSubCat.remove(at: (sender.tag))
然后錯誤:
致命錯誤:索引超出范圍
如何解決這個問題..請指導
var arrSelectedRows:[Int] = []
var arrSubCat:[String] = []
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return getSubCategory?.result?.sub_categories?.count ?? 0
}
var removeIndex: Int?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "EditLangTableVIewCell", for: indexPath) as! EditLangTableVIewCell
let id = getSubCategory?.result?.sub_categories?[indexPath.row].id ?? 0
if arrSelectedRows.contains(id){
cell.langSelectButn.setImage(UIImage(systemName: "checkmark"), for: .normal)
}else{
cell.langSelectButn.setImage(UIImage(named: "checkbox_inactive"), for: .normal)
}
cell.langSelectButn.tag = id
cell.langSelectButn.addTarget(self, action: #selector(checkBoxSelection(_:)), for: .touchUpInside)
return cell
}
@objc func checkBoxSelection(_ sender:UIButton)
{
print(sender.tag)
if self.arrSelectedRows.contains(sender.tag){
self.arrSelectedRows.remove(at: self.arrSelectedRows.firstIndex(of: sender.tag)!)
arrSubCat.remove(at: (sender.tag))
}else{
self.arrSelectedRows.append(sender.tag)
print("arrayof selected row ids \(arrSelectedRows)")
if let selectedSubcat = getSubCategory?.result?.sub_categories{
for singleSubcat in selectedSubcat{
if sender.tag == singleSubcat.id{
arrSubCat.append(singleSubcat.title ?? "")
}
}
}
print("array of subcat title \(arrSubCat)")
}
self.tableView.reloadData()
}
uj5u.com熱心網友回復:
修改checkBoxSelection()方法代碼如下
if self.arrSelectedRows.contains(sender.tag){
if let selectedIndex = self.arrSelectedRows.firstIndex(of: sender.tag) {
self.arrSelectedRows.remove(at: selectedIndex)
arrSubCat.remove(at: selectedIndex)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/471265.html
下一篇:反應原生:按下時更改組件道具
