聲明變量
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è)置背景顏色
}
}