我目前有这个(伪)代码:
var selectedCell: UICollectionViewCell?
override func viewDidLoad() {
super.viewDidLoad()
...
#initialize all objects and pull data from the server to fill the cells
UIView.animate(withDuration: 0, animations: {
self.dataCollectionView.reloadData()
}, completion: {(finished) in
let indexPath = IndexPath(row: 0, section: 0)
self.dataCollectionView.selectItem(at: indexPath, animated: true, scrollPosition: .top)
self.collectionView(self.dataCollectionView, didSelectItemAt: indexPath)
})
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! DataCollectionViewCell
if !selectedCell {
cell.layer.borderWidth = 1
}
else {
cell.layer.borderWidth = 2
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAtindexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
selectedCell = cell
cell.image = SomeImageFromServer
cell.layer.borderWidth = 2
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
cell.layer.borderWidth = 1
}
我的想法是,此代码将在加载集合视图后立即选择第一个单元格,并且确实如此。问题是它也选择了最后一个单元格,但是从不为最后一个单元格调用didSelectItemAtindexPath,只调用第一个单元格。
我尝试使用let indexPath = IndexPath(row: 1, section: 0)
选择第二个单元格,并且一旦加载了集合视图就选择了第二个单元格,并且没有按照您的想法选择最后一个单元格。
选择任何单元格后,将取消选择最后一个单元格。
所以我的假设是,这不是认为细胞被选中的代码"但由于某种原因,它给所选择的细胞一个选定的细胞边界"但仅当第一个选定的单元格是第一个时。有什么想法吗?
答案 0 :(得分:1)
尝试将边框设置移动到单元格中,UICollectionView将自动管理边框宽度:
//Swift3
class TestCollectionViewCell: UICollectionViewCell {
override func awakeFromNib() {
super.awakeFromNib()
self.layer.borderWidth = 1 //Default border width
}
override var isSelected: Bool {
didSet{
if self.isSelected {
self.layer.borderWidth = 2
}
else{
self.layer.borderWidth = 1
}
}
}
}