我具有要选择和取消选择tableview单元格的单元格,但是我无法做到这一点。
这是我的代码:
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")
}
}
}
如果我点击单元格,我希望它被选中,然后将颜色更改为蓝色,如果我再次点击该单元格,我要取消选择,并将颜色更改为绿色,但是上面的代码无法正常工作..... 请帮助我
答案 0 :(得分:1)
在swift5中选择取消选择表格视图单元格
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
}
}
}
}
答案 1 :(得分:0)
我从未尝试过更改背景色,但是我根据选择更改了单元格。在执行表视图时,我总是执行自定义类,因此我可以更轻松地处理这些情况。试试这个:
CustomCell类:UITableViewCell {
override func setSelected(_ selected: Bool, animated: Bool) {
self.coverView.backgroundColor = selected ? .blue : .green
}
}
答案 2 :(得分:0)
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
}
}