簡體   English   中英

在 Swift iOS 中選擇 collectionView Cell 時更改 label 顏色

[英]Change label color when collectionView Cell is selected in Swift iOS

我正在嘗試在我的應用程序中按類型創建過濾器,並且我進行了 collectionView 設置,並且一切正常。

我唯一的問題是讓 collectionView 單元格文本標簽在被選中時更改顏色為白色,而在未選中時更改為黑色。

但它似乎無法正常工作,因為它會更改未選中的單元格的顏色,並且在取消選中后不會清除顏色。

有什么幫助嗎?

謝謝你。

這是我的代碼:

var label:UILabel!
var typeText:String?
var type = ["All","Coffee Shops","Pizza Places","Restaurants","Desserts"]


extension HomeTableViewController: UICollectionViewDataSource {
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return type.count
    }
    func numberOfSections(in collectionView: UICollectionView) -> Int {
    
        return 1
        
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath)
        
        let type = self.type[indexPath.row]
      
        cardView = UIView(frame: CGRect(x:0, y:0, width:myCell.frame.size.width, height:myCell.frame.size.height))
        cardView.backgroundColor = UIColor(red:0.00, green:0.00, blue:0.00, alpha:0.02)
        cardView.layer.cornerRadius = 8
        cardView.layer.shadowOffset = CGSize(width: 0.2, height: 0.2)
        cardView.layer.shadowRadius = 1
        cardView.layer.shadowOpacity = 0.4
        cardView.layer.borderColor = CGColor(red:0.00, green:0.00, blue:0.00, alpha:0.2)
        cardView.layer.borderWidth = 0.4
        cardView.autoresizesSubviews = true
        cardView.clipsToBounds = true
        
        label = UILabel(frame: CGRect(x:0, y:0, width:cardView.frame.size.width, height:cardView.frame.size.height))
        label.textAlignment = .center
        label.textColor = UIColor(red:0.00, green:0.00, blue:0.00, alpha:0.8)
        label.font = UIFont.systemFont(ofSize: 9, weight: .semibold)
        label.text = type
        
        myCell.addSubview(cardView)
        cardView.addSubview(label)
        
        return myCell
    }
}

extension HomeTableViewController: UICollectionViewDelegate {
 
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
      
        typeText = self.type[indexPath.row]
        
        let backgroundView = UIView()
        backgroundView.backgroundColor = UIColor(red: 0.99, green: 0.71, blue: 0.25, alpha: 1.00) /*ffb233 feb947  fcb53f*/
        backgroundView.layer.cornerRadius = 8
        backgroundView.layer.shadowOffset = CGSize(width: 0.3, height: 0.3)
        backgroundView.layer.shadowRadius = 1
        backgroundView.layer.shadowOpacity = 0.4
        backgroundView.layer.borderColor = UIColor.white.cgColor
        backgroundView.layer.borderWidth = 0.5
        backgroundView.autoresizesSubviews = true
        backgroundView.clipsToBounds = true

        
       if let selectedCell:UICollectionViewCell = collectionView.cellForItem(at: indexPath){
        selectedCell.selectedBackgroundView = backgroundView
        label.textColor = .white
        }
}

   func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        let cellToDeselect:UICollectionViewCell = collectionView.cellForItem(at: indexPath)!
        cellToDeselect.contentView.backgroundColor = UIColor.clear
        label.textColor = .black
    }

首先,您不應該在cellForItemAt添加子視圖 ... 單元格被重用,並且最終在每個單元格中多次添加子視圖。

相反,當它被實例化時,在你的單元類中添加你的子視圖。

然后,將其添加到您的單元格類中:

override var isSelected: Bool {
    didSet {
        label.textColor = isSelected ? .white : .black
    }
}

無需在控制器中對didSelectItemAtdidDeselectItemAt執行任何didDeselectItemAt


編輯- 這是一個非常簡單的例子......

細胞類:

class MyCardCell: UICollectionViewCell {
    let label: UILabel = {
        let v = UILabel()
        return v
    }()
    let cardView: UIView = {
        let v = UIView()
        return v
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    func commonInit() -> Void {
        
        cardView.backgroundColor = UIColor(red:0.00, green:0.00, blue:0.00, alpha:0.02)
        cardView.layer.cornerRadius = 8
        cardView.layer.shadowOffset = CGSize(width: 0.2, height: 0.2)
        cardView.layer.shadowRadius = 1
        cardView.layer.shadowOpacity = 0.4
        cardView.layer.borderColor = CGColor(red:0.00, green:0.00, blue:0.00, alpha:0.2)
        cardView.layer.borderWidth = 0.4
        cardView.clipsToBounds = true
        
        label.textAlignment = .center
        label.textColor = UIColor(red:0.00, green:0.00, blue:0.00, alpha:0.8)
        label.font = UIFont.systemFont(ofSize: 9, weight: .semibold)

        [cardView, label].forEach { v in
            v.translatesAutoresizingMaskIntoConstraints = false
        }
        cardView.addSubview(label)
        contentView.addSubview(cardView)
        
        let g = contentView.layoutMarginsGuide
        
        NSLayoutConstraint.activate([
            
            cardView.topAnchor.constraint(equalTo: g.topAnchor),
            cardView.leadingAnchor.constraint(equalTo: g.leadingAnchor),
            cardView.trailingAnchor.constraint(equalTo: g.trailingAnchor),
            cardView.bottomAnchor.constraint(equalTo: g.bottomAnchor),

            label.centerYAnchor.constraint(equalTo: cardView.centerYAnchor),
            label.leadingAnchor.constraint(equalTo: cardView.leadingAnchor, constant: 12.0),
            label.trailingAnchor.constraint(equalTo: cardView.trailingAnchor, constant: -12.0),

        ])
    
    }
    
    override var isSelected: Bool {
        didSet {
            label.textColor = isSelected ? .white : .black
            // see the difference between setting
            //      cardView.backgroundColor
            //  or
            //      contentView.backgroundColor
            cardView.backgroundColor = isSelected ? UIColor(red: 0.99, green: 0.71, blue: 0.25, alpha: 1.00) : UIColor(red:0.00, green:0.00, blue:0.00, alpha:0.02)
            //contentView.backgroundColor = isSelected ? UIColor(red: 0.99, green: 0.71, blue: 0.25, alpha: 1.00) : UIColor(red:0.00, green:0.00, blue:0.00, alpha:0.02)
        }
    }
}

和一個示例視圖控制器類:

class TestCardCollectionVC: UIViewController {
    
    var collectionView: UICollectionView!

    var type: [String] = ["All","Coffee Shops","Pizza Places","Restaurants","Desserts"]

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let fl = UICollectionViewFlowLayout()
        fl.scrollDirection = .horizontal
        fl.minimumLineSpacing = 0
        fl.minimumInteritemSpacing = 0
        fl.estimatedItemSize = CGSize(width: 50, height: 40)

        collectionView = UICollectionView(frame: .zero, collectionViewLayout: fl)
        
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(collectionView)
        
        let g = view.safeAreaLayoutGuide
        NSLayoutConstraint.activate([
            collectionView.topAnchor.constraint(equalTo: g.topAnchor),
            collectionView.leadingAnchor.constraint(equalTo: g.leadingAnchor),
            collectionView.trailingAnchor.constraint(equalTo: g.trailingAnchor),
            collectionView.heightAnchor.constraint(equalToConstant: 40.0)
        ])

        collectionView.backgroundColor = .systemBackground
        
        collectionView.register(MyCardCell.self, forCellWithReuseIdentifier: "cardCell")

        collectionView.dataSource = self
        collectionView.delegate = self
    }
    
}

extension TestCardCollectionVC: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return type.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let c = collectionView.dequeueReusableCell(withReuseIdentifier: "cardCell", for: indexPath) as! MyCardCell
        c.label.text = type[indexPath.item]
        return c
    }

}

啟動時的輸出(未選擇單元格):

在此處輸入圖片說明

選擇第三個單元格:

在此處輸入圖片說明

選擇第四個單元格:

在此處輸入圖片說明

我試圖使用我自己的項目找到解決方案。 也許你應該試試這個

class NatureCollectionViewCell: UICollectionViewCell {

@IBOutlet weak var natureItemsImage: UIImageView!
@IBOutlet weak var natureItemsNameLable: UILabel!


// This part you will need. just change the labels name
override var isSelected: Bool {
    
    didSet {
        if self.isSelected {
            self.natureItemsNameLable.textColor = .white
            
        } else {
            self.natureItemsNameLable.textColor = .black
        }
    }
}

}

在子類 UICollectionViewCell 的單元格中,只需通過標簽上的highlightedTextColor屬性設置顏色突出顯示和正常狀態。

class TypeCell: UICollectionViewCell {

      @IBOutlet weak var titleLabel: UILabel!

      override func awakeFromNib() {
         super.awakeFromNib()
         titleLabel.textColor = .white
         titleLabel.highlightedTextColor = .green
      }
 }

1): 內部單元格添加視圖和一個 label。

2):為兩者創建出口。

@IBOutlet weak var titleLabel : UILabel!
@IBOutlet weak var cellBgView: UIView!

3): 在您的 collectionView 單元格 class 中粘貼以下代碼。

 override var isSelected: Bool {
        didSet {
            titleLabel.textColor = isSelected ? .white : .black
            cellBgView.backgroundColor = isSelected ? .AppRed : .systemBackground
           
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM