Reputation: 392
I have 2 buttons and 1 collectionView on a ViewController. On clicking one button the collectionView's data source changes and It is reloaded to change the options shown in the collectionView's cells, and on clicking the other button different options are shown. I want to change the font of the text in the label(this label is present inside the cell) of the cell selected by the user.So, for that I did the following
var previouslySelectedCell: IndexPath? = IndexPath(row: 0, section: 0)
var leftOutPreviouslySelectedCell: IndexPath?
In cellForItemAt:
cell?.frameNameLabel.font = UIFont.Book16
if indexPath == previouslySelectedCell {
cell?.frameNameLabel.font = UIFont.Medium16
}
In didSelectItemAt:
if previouslySelectedCell != nil {
if let previousCell = collectionView.cellForItem(at: previouslySelectedCell!) as? FramePhotoCell {
previousCell.frameNameLabel.font = UIFont.Book16
} else {
leftOutPreviouslySelectedCell = previouslySelectedCell
}
}
let cell = collectionView.cellForItem(at: indexPath) as! FramePhotoCell
cell.frameNameLabel.font = UIFont.Medium16
previouslySelectedCell = indexPath
In willDisplay:
if indexPath == leftOutPreviouslySelectedCell {
(cell as! FramePhotoCell).frameNameLabel.font = UIFont.Book16
leftOutPreviouslySelectedCell = nil
}
Problem with this approach is that if I select a cell in one collectionView an then when I tap on a button which changes its dataSource and a new reloaded collectionView with new data appears; There too the previously selected cell (selected in previous version of collectionView) seems to be selected/highlighted, as that cell's IndexPath is there in the previously selected Cell. I don't want to erase values of previously selected cell on switching to the other collectionView, as if a user selects one cell and then moves to the other version of collectionView, and then comes back to the previous version of collection view by tapping on the 2 buttons given, The previously selected cell should still be in the selected mode. What should I do?
Upvotes: 1
Views: 389
Reputation: 9503
Take an array as arrSelectedIndex
In OnBtnClick
if index is not in array{
1. add index in array
2. reload your data
}
else if index is in array{
1. remove index in array
2. reload your data
}
In cellForRow
cell.btn.tag = indexPath.row
1. check cuurent indexPath is in the `arrSelectedIndex` or not.
2. if step1 true{
show your hightlighted data
}
else{
show default data
}
hope this helps you.
Upvotes: 0