2022, for anyone using TVOS
Thanks to the great answer from @matt we know how to do this now.
I found two insurmountable problems in TVOS project.
There's basically a bug where it inserts a large left content inset for some reason. The only way to get rid of it is to override safeAreaInsets
.
Separate issue: Strangely if you just set the layout "inline" in the view controller as in the accepted answer from @matt, there's a bug or misbehaviour where the scroll does not start properly on the left, but in a random central position. (Even worse if you have many of the collection views on the screen, they all behave erraticlly.) Miraculously if you subclass instead, for some reason that fixes it (I guess due to the bringup order somehow).
Hence
class TightCollectionView: UICollectionView {
override var safeAreaInsets: UIEdgeInsets {
get {
return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
set {
}
}
and then ...
func layout() -> UICollectionViewCompositionalLayout {
let itemSize = NSCollectionLayoutSize(widthDimension: .absolute(500), heightDimension: .absolute(300))
let item = NSCollectionLayoutItem(layoutSize: itemSize)
let groupSize = NSCollectionLayoutSize(widthDimension: .absolute(500), heightDimension: .absolute(300))
let group = NSCollectionLayoutGroup.vertical(layoutSize: groupSize, subitem: item, count: 1) // one count for single row
group.edgeSpacing = NSCollectionLayoutEdgeSpacing(leading: .fixed(0), top: .fixed(0), trailing: .fixed(0), bottom: .fixed(0))
let section = NSCollectionLayoutSection(group: group)
section.interGroupSpacing = 20
let config = UICollectionViewCompositionalLayoutConfiguration()
config.scrollDirection = .horizontal
let layout = UICollectionViewCompositionalLayout(section: section, configuration:config)
return layout
}
and thus ...
var bringup: Bool = true // I hate doing this but there's no really solid alternative in UIKit, thanks Apple
override func layoutSubviews() {
if bringup {
collectionViewLayout = layout()
bringup = false
}
super.layoutSubviews()
}
}
Footnote - note that code like this:
// section.contentInsetsReference = .none
// config.contentInsetsReference = .none
Seemingly does nothing at all on TVOS. I fiddled with it for hours.
Footnote
.absolute(500)
I could really only get solid results on all gen. of TVOS by just setting everything absolutely in the compositional layout. For now (2022!) it just seems too flakey otherwise.