我有这段代码可以在选择单元格时更改单元格的颜色和字体样式。它工作正常,除了当我从父 View 的 init(frame:) 函数中手动选择它时。它应该将颜色更改为蓝色,将字体样式更改为粗体,当我从测试设备切换它时,它工作得非常好。但是,当我尝试以编程方式设置默认选定项时,它仅将样式更改为粗体,但颜色仍然与未选定的相同,即。灰色的。
这是单元格的类:
class ItemCollectionCell: UICollectionViewCell {
@IBOutlet weak var titleLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func setupCell(title: String)
{
titleLabel.text = title
titleLabel.textColor = UIColor.gray
}
override var isSelected: Bool{
didSet {
titleLabel.textColor = isSelected ? UIColor.blue : UIColor.gray
titleLabel.font = isSelected ? UIFont.boldSystemFont(ofSize: titleLabel.font.pointSize) : UIFont.systemFont(ofSize: titleLabel.font.pointSize)
}
}
}
其中包含 Collection View 的父 View :
class ItemsView: UIView, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
let reuseableCellId = "itemCell"
let nibItemCell = UINib(nibName: "ItemCollectionCell", bundle: nil)
//Collection view for items
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.dataSource = self
cv.delegate = self
//Create subview (collection) for the menu buttons
//Register cell's XIB and class
cv.register(nibItemCell, forCellWithReuseIdentifier: reuseableCellId)
//Set subview BG color
cv.backgroundColor = UIColor.white
cv.contentInsetAdjustmentBehavior = .never
return cv
}()
override init(frame: CGRect) {
super.init(frame: frame)
//Add subview
self.addSubview(collectionView)
//Set subview constraints
self.addConstraintsWithFormat("H:|[v0]|", views: collectionView)
self.addConstraintsWithFormat("V:|[v0]|", views: collectionView)
let selectedPath = IndexPath(item: 0, section: 0)
collectionView.selectItem(at: selectedPath, animated: false, scrollPosition: .centeredVertically)
}
//... all the other funcs
}
这里出了什么问题?我该如何解决?谢谢。
最佳答案
在选择单元格之前, Collection View 似乎没有重新加载。另外,您是否尝试过手动更新 isSelected?
关于ios - 以编程方式选择 Collection View 单元格无法执行单元格的某些 isSelected 例程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48375919/