點擊TableView 多選 cell

聲明變量

let cellId = "TestTableViewCell"
let dataArray = ["111","222","333","444","555","666","777","888","999","000"]
var selectArray = [String]()
override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.register(UINib.init(nibName: cellId, bundle: Bundle.main), forCellReuseIdentifier: cellId)
    }
extension ViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        // 1.獲取cell
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! TestTableViewCell
        // 2.獲取數(shù)據(jù)
        let str = self.dataArray[indexPath.row]
        // 3.設(shè)置數(shù)據(jù)
        cell.titleLabel.text = str
        // 4.設(shè)置選中狀態(tài)(目前采用更改背景顏色)
        var backgroundCorlor = UIColor.clear // 默認為透明
        if self.selectArray.contains(str) {
            backgroundCorlor = UIColor.blue // 如果已選擇(在選中數(shù)組中)則更改背景顏色
        }
        cell.backgroundColor = backgroundCorlor  // 設(shè)置背景顏色
        
        // 5.返回cell
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 120
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        // 選擇處理
        /// 1.獲取當前點擊的cell
        let cell = tableView.cellForRow(at: indexPath) as! TestTableViewCell
        /// 2.獲取數(shù)據(jù)
        let str = self.dataArray[indexPath.row]
        /// 3.判斷選中狀態(tài)
        var backgroundCorlor = UIColor.blue
        if self.selectArray.contains(str) {
            // 已選擇則移除,并更新cell背景
            if let index = self.selectArray.index(of: str) {
              self.selectArray.remove(at: index) // 移除選中
            }
            
            backgroundCorlor = UIColor.clear // 設(shè)置透明背景
        } else { // 未選中
            self.selectArray.append(str) // 添加至數(shù)組中
        }
        
        cell.backgroundColor = backgroundCorlor // 設(shè)置背景顏色
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容