Making UICollectionView's accessible inside UITableView's
Apple is handling a lot of accessibility features automatically for us when we use UIKit components like UITableView
's and UICollectionView
's.
Though I've noticed it doesn't work out of the box when you try a design like the App Store app, with a UICollectionView
embedded in a UITableView
.
When using VoiceOver, you will not be able to go through all items of your UICollectionView
. Here's a video presenting the problem π

To fix this issue, there's one weird trick. Simply subclass UICollectionView
:
class AccessibleCollectionView: UICollectionView {
override func accessibilityElementCount() -> Int {
guard let dataSource = dataSource else {
return 0
}
return dataSource.collectionView(self, numberOfItemsInSection: 0)
}
}
or for supporting UICollectionView
's with several sections:
class AccessibleCollectionView: UICollectionView {
override func accessibilityElementCount() -> Int {
guard let dataSource = dataSource else {
return 0
}
let numberOfSections = dataSource.numberOfSections?(in: self) ?? 1
var count = 0
for section in 0..<numberOfSections {
count += dataSource.collectionView(self, numberOfItemsInSection: section)
}
return count
}
}
And... tadaaaa π
