[英]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.