【发布时间】:2021-03-31 09:14:10
【问题描述】:
在选择自定义 UICollectionView 单元格时,我一直在尝试更改其背景颜色和标签颜色,但似乎无法真正弄清楚这一点。当前的问题是,当单元格被选中时,它会更改背景颜色,但标签会完全消失(它会创建具有所选背景颜色的新单元格并将其放在旧单元格上)。我有一个自定义 UICollectionViewCell 类,我在其中设置初始背景颜色和标签:
class UnitCollectionViewCell: UICollectionViewCell {
let cornerRadius: CGFloat = 27
var bigLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var isSelected: Bool {
didSet {
self.contentView.layer.cornerRadius = cornerRadius
self.contentView.backgroundColor = isSelected ? UIColor(named: "warmRed") : .none
}
}
func setupView() {
backgroundColor = UIColor(named: "warmRed")?.withAlphaComponent(0.4)
layer.cornerRadius = cornerRadius
configureUnitViewLabels()
}
func configureUnitViewLabels() {
bigLabel.font = .boldSystemFont(ofSize: 30)
bigLabel.textColor = UIColor(named: "darkWhite")
bigLabel.textAlignment = .left
bigLabel.translatesAutoresizingMaskIntoConstraints = false
addSubview(bigLabel)
setBigLabelConstraints()
}
func setBigLabelConstraints() {
bigLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10).isActive = true
bigLabel.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 15).isActive = true
bigLabel.rightAnchor.constraint(equalTo: contentView.safeAreaLayoutGuide.rightAnchor, constant: 5).isActive = true
bigLabel.heightAnchor.constraint(equalToConstant: 30).isActive = true
}
}
在我的 ViewController 类中,我目前在 cellForItemAt 方法中声明自定义单元格:
let unitCell = collectionView.dequeueReusableCell(withReuseIdentifier: "unitCell", for: indexPath) as! UnitCollectionViewCell
目前的结果:
期望的结果:
到目前为止我尝试了什么:
-
我曾尝试在我的自定义单元格类中使用
isSelected方法(请参阅上面我的自定义单元格类中的代码),但如前所述,它会创建新单元格并将其置于旧单元格之上。 -
我已经尝试将
didSelectItemAt和didDeselectItemAt方法与 dequeueReusableCell(withReuseIdentifier:,for: IndexPath) 和 cellForItem(at: IndexPath) 一起使用,但它们的工作原理与前面提到的isSelected方法基本相同。 -
我也尝试在
isSelected方法中创建新的 UILabel,但是标签没有设置为应该在cellForItemAt方法中设置的文本。
如果需要任何其他代码,请告诉我。谢谢!
【问题讨论】:
标签: ios swift uicollectionviewcell