We have a UICollectionViewCell that is being manually selected when the screen loads. This cell should always be selected during the lifetime of the screen and there is always only one cell in this particular section of the collection view.
override public func cellForItem(at index: IndexPath) -> UICollectionViewCell {
let cell = collectionContext.dequeueReusableCell(withReuseIdentifier: cellStyle.reuseIdentifier, for: index) as! AccountSelectorSavingsPotAccountCompactCell
cell.configure(for: savingsPot.savingsAccount)
cell.isReadOnlyCell = true
cell.isSelected = true
return cell
}
Please note, the .isReadOnlyCell doesn't change the issue. Switching the order with .isSelected, or even removing the line altogether, does not fix the issue.
And here we have the overridden 'isSelected' on the cell itself:
override public var isSelected: Bool {
didSet {
if self.isSelected == false {
self.selectedPotUUID = nil
}
styleView(selected: self.isSelected, showTableIfSelected: !self.isReadOnlyCell)
if self.account != nil {
self.potsTableView.reloadData()
}
}
}
On iOS 13, after the cell.isSelected is set to true, everything is fine and the cell remains selected. However, on iOS 15, after this occurs, the didSet{} is triggered again, this time because isSelected was set to false.
This only happens on iOS 15 (I haven't tested on 14) and when this second event occurs, the stack trace does not help me. It doesn't reveal where isSelected is getting set to false and breakpoints everywhere else that might suggest a reloadData() is getting called somewhere don't trigger. I believe that the cell is getting automatically set to false again due to some lifecycle issue but I haven't been able to track down where this might be occurring. The lack of a stack trace is also mystifying.
Is this a known issue n iOS 15, or is there some event I'm overlooking?
CodePudding user response:
You should not be setting .isSelected
yourself.
The UICollectionView
keeps track of the selected cell and sets .isSelected
when each cell is going to be displayed.
The proper way to "pre-select" a cell is to call (at the end of viewDidLoad()
, for example):
let preSelectPath = IndexPath(item: 2, section: 0)
collectionView.selectItem(at: preSelectPath, animated: false, scrollPosition: .top)
Obviously, change the index path values to the cell you want selected, and replace .top
with your desired scrollPosition.