I tried to solve this problem since hours and didn't find a proper solution. I want to have a custom UICollectionView with a segmented control in the header. Changing the segmented control index should render the cells differently. So far I can display the segmented control in the header of my collectionView but changing the content of the collectionView inside of my UserSearchHeader doesn't work.
I created a custom UICollectionView called UserSearchController which is a Subclass of UICollectionView and conforms the UICollectionViewDelegateFlowLayout protocol.
class UserSearchController: UICollectionViewController,
UICollectionViewDelegateFlowLayout, UISearchBarDelegate { ....
My custom collectionView UserSearchController has a custom header (UserSearchHeader) and custom cells (UserSearchCell).
collectionView?.register(UserSearchCell.self, forCellWithReuseIdentifier: cellId)
collectionView?.register(UserSearchHeader.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerId")
The UserSearchHeader contains the segmented control.
class UserSearchHeader: UICollectionViewCell {
var segmentedControl: UISegmentedControl = {
let sc = UISegmentedControl(items: ["Username", "Hashtag"])
sc.translatesAutoresizingMaskIntoConstraints = false
sc.tintColor = UIColor.black
sc.selectedSegmentIndex = 0 // automatically highlight
// sc.addTarget(self, action: #selector(segmentedChange), for: .valueChanged)
return sc
}() .....
If the segmentedIndex is 0 I want to render the cells with the UserSearchCell class if the segmentedIndex is 1 I want to render it with a different cellClass (Clicking the segmented control). How can I achieve this behavior with these different classes. shall I use the cellForItem at method inside of the UserSearchController to check the status of the segmented control. But how can I do this when the segmented control is defined in the UserSearchHeader class .
override func collectionView(_ collectionView:
UICollectionView, cellForItemAt indexPath: IndexPath) ->
UICollect. ionViewCell { if segmentedControl.segmentedIndex = 0 ....}
tried using Use the
scopeButtonTitles
property?Have a look at this question for more details. Basically you use the
EDIT: Please find below the missing pieces described in the link provided initially. There is no need to add the header from a NIB.
First, you add properties for your search & results controllers:
Then, in
viewDidLoad
you add this:Then you need to add this function to your class:
Finally, you add the function I was describing initially:
searchBar:selectedScopeButtonIndexDidChange: