tableView列表中會(huì)有單選和多選功能鲫骗,cell多是自定義榨了,網(wǎng)上的一些文章邏輯都比較復(fù)雜站削,主要問(wèn)題還是要梳理清楚。實(shí)現(xiàn)方式:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:FamilyRoomTableViewCell! = tableView.dequeueReusableCell(withIdentifier: "room", for: indexPath) as? FamilyRoomTableViewCell
cell.selectionStyle = .none
cell.selectedBtn.tag = indexPath.row + 1000
//模型賦值
cell.setmodel(model: self.roomListArray![indexPath.row])
cell?.changeModelBlock = { (tag) ->Void in
cell.roomModel = self.roomListArray![tag-1000]
if cell.roomModel?.isRoomSelected == "0" {
cell.roomModel?.isRoomSelected = "1"
self.roomNameArray.append((cell.roomModel?.groupName)!)
}else {
cell.roomModel?.isRoomSelected = "0"
//array沒(méi)有移除object元素的方法苛预,所以采用filter函數(shù)進(jìn)行過(guò)濾
//使用nsmutableArray方法移除當(dāng)前的object句狼,如果是可選類型,打印出來(lái)的值帶有option字樣热某,如果不是可選類型腻菇,打印出來(lái)的值為unicode碼(暫時(shí)不知道原因)
self.roomNameArray = self.roomNameArray.filter({$0 != cell.roomModel?.groupName})
}
//重新賦值這一步很關(guān)鍵
self.roomListArray![tag-1000] = cell.roomModel!
self.familyTableView.reloadData()
print("**********當(dāng)前的房間數(shù)組*********\(String(describing: self.roomNameArray))")
}
return cell
}
思路:根據(jù)btn的tag與cell的indexPath關(guān)聯(lián),模型里手動(dòng)添加isRoomSelected字段判斷是否選中昔馋,如果是放在該方法根據(jù)isRoomSelected去改變btn的背景圖片的選擇狀態(tài)筹吐,由于cell的重用機(jī)制,在滑動(dòng)的時(shí)候會(huì)導(dǎo)致btn的圖片勾選狀態(tài)錯(cuò)亂秘遏。
解決問(wèn)題關(guān)鍵:將選中狀態(tài)與model進(jìn)行綁定丘薛,解決重用問(wèn)題
cell中的代碼
func setmodel(model:HouseDeviceGroupModel?) {
roomModel = model
roomNameLabel.text = model?.groupName
selectedBtn.isSelected = (model?.isRoomSelected == "1")
// // 按鈕默認(rèn)選中
if selectedBtn.isSelected {
//選中
selectedBtn.setImage(UIImage(named: "xuanze_on"), for: .normal)
}else {
//不選中
selectedBtn.setImage(UIImage(named: "xuanze_off"), for: .normal)
}
}
最終效果如下:
完美解決重用問(wèn)題