As the question, I'm trying to add an "index titles" in a collection view for a fast navigation of the contents of my UIColletionView
.
I've read that, starting from iOS 10, method like indexTitles(for:)
and collectionView(_:indexPathForIndexTitle:at:)
can help me in that as in the UITableViews . But I'm not getting any result! Have you figured out how to use those methods? Thanks in advance for any help.
If you look at UICollectionView.h
, indexTitlesForCollectionView
is only available in tvos:
/// Returns a list of index titles to display in the index view (e.g. ["A", "B", "C" ... "Z", "#"])
- (nullable NSArray<NSString *> *)indexTitlesForCollectionView:(UICollectionView *)collectionView API_AVAILABLE(tvos(10.2));
You might have read Apple's documentation, which states that indexTitle methods are available for iOS 10.3+ and tvOS 10.2+: https://developer.apple.com/documentation/uikit/uicollectionviewdatasource/2851455-indextitles
I tried implementing it on iOS and it just doesn't work, which leads me to believe that somehow they made a mistake in the documentation.
I got the titles working on iPhones only by adding the following to my data source:
func indexTitles(for collectionView: UICollectionView) -> [String]? {
guard !RunUtilities.isIpad else { return nil }
return Array(Set(objects.map{ String($0.name.prefix(1)) })).sorted(by: { $0 < $1 })
}
func collectionView(_ collectionView: UICollectionView, indexPathForIndexTitle title: String, at index: Int) -> IndexPath {
guard let index = objects.firstIndex(where: { $0.name.prefix(1) == title }) else {
return IndexPath(item: 0, section: 0)
}
return IndexPath(item: index, section: 0)
}
EDIT: It looks like this is working from iOS 14 onwards. I installed the 13.4 runtime and the titles don't show.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.