swift 在IOS 15中,收集视图所选单元格背景视图颜色不变

cuxqih21  于 2022-12-10  发布在  Swift
关注(0)|答案(1)|浏览(143)

当集合视图单元格被选中时,单元格背景视图和该单元格中的其他标签应该改变颜色。下面的代码适用于ios 15以下的操作系统。如果我在下面的代码中将didSet更改为willSet,它在iOS 15下工作,但在iOS 15以下不工作。是否有解决方案可以更改所选自定义单元格的颜色?我还添加了集合视图委托和数据源方法代码。

override var isSelected: Bool{

        didSet{
            if self.isSelected
            {
                super.isSelected = true
                lblName.textColor = .white
                cellBGView.backgroundColor = .themeColor
                cellInfoBtn.tintColor = .white

            }
            else
            {
                super.isSelected = false
                lblName.textColor = .themeColor
                cellBGView.backgroundColor = .white
                cellInfoBtn.tintColor = .themeColor
            }
        }
  func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
 { 
selectIndex = indexPath.row 
let cell = collectionView.cellForItem(at: indexPath) as! CustomCollectionCell 
selectedIndexPath = indexPath 
selectIndexSec = indexPath.section 
collectionView.reloadData() 
}

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCollectionCell", for: indexPath) as! CustomCollectionCell cell.cellInfoBtn.tag = indexPath.row 
cell.cellInfoBtn.addTarget(self, action: #selector(infoBtnTapped(_:)), for: .touchUpInside) 
if selectIndex == indexPath.row { cell.isSelected=true } 
else { cell.isSelected=false }
 return cell 
}

我尝试了上述代码,我需要找到一个共同的解决方案,为旧版本以及版本以上15。如果已经有一个答案存在,请重定向我到它。

fwzugrvs

fwzugrvs1#

你做了很多额外的工作。
UICollectionView使用.indexPathsForSelectedItems跟踪它自己的选择,因此不需要使用selectedIndexPathselectIndexSec进行额外的跟踪。
此外,如果要覆盖isSelected,则无需调用.reloadData()
下面是一个完整的示例--我添加了lblNamecellBGView,但没有添加按钮:

class AutoHighlightCell: UICollectionViewCell {
    
    let lblName = UILabel()
    let cellBGView = UIView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    func commonInit() {
        lblName.textAlignment = .center
        
        [cellBGView, lblName].forEach { v in
            v.translatesAutoresizingMaskIntoConstraints = false
        }
        cellBGView.addSubview(lblName)
        contentView.addSubview(cellBGView)
        
        let g = contentView.layoutMarginsGuide
        NSLayoutConstraint.activate([
            
            cellBGView.topAnchor.constraint(equalTo: g.topAnchor, constant: 0.0),
            cellBGView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 0.0),
            cellBGView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: 0.0),
            cellBGView.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: 0.0),
            
            lblName.topAnchor.constraint(equalTo: cellBGView.topAnchor, constant: 16.0),
            lblName.leadingAnchor.constraint(equalTo: cellBGView.leadingAnchor, constant: 24.0),
            lblName.trailingAnchor.constraint(equalTo: cellBGView.trailingAnchor, constant: -24.0),
            lblName.bottomAnchor.constraint(equalTo: cellBGView.bottomAnchor, constant: -16.0),
            
        ])
        
        contentView.layer.borderWidth = 1.0
        contentView.layer.borderColor = UIColor.black.cgColor
        
        // set default non-selected properties
        lblName.textColor = .blue
        cellBGView.backgroundColor = .yellow
        
    }
    
    override var isSelected: Bool {
        didSet {
            lblName.textColor = isSelected ? .white : .blue
            cellBGView.backgroundColor = isSelected ? .systemGreen : .yellow
        }
    }
    
}

class AutoHighlightCollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
    
    var collectionView: UICollectionView!
    
    let instructionLabel: UILabel = {
        let v = UILabel()
        v.textAlignment = .center
        v.text = "Tap Here"
        v.numberOfLines = 0
        return v
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let fl = UICollectionViewFlowLayout()
        fl.estimatedItemSize = CGSize(width: 80, height: 50)
        fl.scrollDirection = .horizontal
        
        collectionView = UICollectionView(frame: .zero, collectionViewLayout: fl)

        collectionView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(collectionView)
        
        instructionLabel.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(instructionLabel)

        let g = view.safeAreaLayoutGuide
        NSLayoutConstraint.activate([
            
            collectionView.topAnchor.constraint(equalTo: g.topAnchor, constant: 80.0),
            collectionView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
            collectionView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
            collectionView.heightAnchor.constraint(equalToConstant: 80.0),
            
            instructionLabel.topAnchor.constraint(equalTo: collectionView.bottomAnchor, constant: 60.0),
            instructionLabel.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
            instructionLabel.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
            
        ])
        
        collectionView.register(AutoHighlightCell.self, forCellWithReuseIdentifier: "cell")
        
        collectionView.dataSource = self
        collectionView.delegate = self
        
        // so we can see the collectionView frame
        collectionView.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
        
        let t = UITapGestureRecognizer(target: self, action: #selector(gotTap(_:)))
        instructionLabel.addGestureRecognizer(t)
        instructionLabel.isUserInteractionEnabled = true
        
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 20
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let c = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! AutoHighlightCell
        c.lblName.text = "\(indexPath)"
        return c
    }

    @objc func gotTap(_ g: UITapGestureRecognizer) {
        var s = "Tap Here\n\n"
        if let pth = collectionView.indexPathsForSelectedItems?.first {
            s += "Selected Path: \(pth)"
        } else {
            s += "No Item Selected"
        }
        instructionLabel.text = s
    }
    
}

运行时,它将如下所示:

如果在选择单元格之前轻按“轻按此处”,您将看到:

选择单元格后:
第一次
请注意,当您滚动单元格进出视图时,集合视图将保持“Selected”状态,并且单元格的UI将在override var isSelected中更新......无需担心cellForItemAtdidSelectItemAt中的任何问题

相关问题