[英]How to select deselect tableview cell in swift4
我有帶有單元格的表格視圖,我想選擇和取消選擇表格視圖單元格,但我無法做到。
這是我的代碼:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
//cell.changeTextField
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? TableViewCell {
cell.backgroundColor = UIColor.blue
print("select")
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? TableViewCell {
cell.backgroundColor = UIColor.green
print("deselect")
}
}
}
如果我點擊單元格我希望它被選中並將顏色更改為藍色如果我再次點擊該單元格我想取消選擇並將顏色更改為綠色但我的代碼無法正常工作.....請幫助我
在swift5中選擇取消選擇tableview單元格
class UserCardView: UICollectionViewCell {
@IBOutlet var btnDelete: UIButton!
@IBOutlet var imgView: UIImageView!
@IBOutlet var lblUserName: UILabel!
@IBOutlet var lblBalance: UILabel!
@IBOutlet var rndView: RoundedView!
override var isSelected: Bool{
didSet{
if self.isSelected
{
//This block will be executed whenever the cell’s selection state is set to true
self.rndView.backgroundColor = Common.mainColr
self.lblUserName.textColor = UIColor.white
self.lblBalance.textColor = UIColor.white
}
else
{
//This block will be executed whenever the cell’s selection state is set to false
self.rndView.backgroundColor = UIColor.white
self.lblUserName.textColor = UIColor.black
self.lblBalance.textColor = UIColor.gray
}
}
}
}
我從未嘗試過更改背景顏色,但我根據選擇更改了單元格。 我在做 tableview 時總是做自定義類,這樣我就可以更輕松地處理這些情況。 嘗試這個:
類 CustomCell: UITableViewCell {
override func setSelected(_ selected: Bool, animated: Bool) {
self.coverView.backgroundColor = selected ? .blue : .green
}
}
Swift 5 :只需覆蓋 Cell 中的 isSelected 屬性:
class SimpleAppCell: UITableViewCell {
// MARK: - Properties
override var isSelected: Bool {
didSet {
contentView.backgroundColor = isSelected ? .systemBlue12 : .clear
contentView.layer.cornerRadius = isSelected ? 8 : 0
textLabel?.textColor = isSelected ? .systemBlue : .label
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.