FlowKit icon indicating copy to clipboard operation
FlowKit copied to clipboard

Documentation for collectionViews does not mention initializing the layout but it crashes when not set

Open cwoloszynski opened this issue 6 years ago • 2 comments

Looking to understand how the layout should be initialized to use the collection view and suggest adding this to the documentation.

cwoloszynski avatar Sep 15 '18 22:09 cwoloszynski

Not sure, but I think, that when you create UICollectionView from code, then you need to create Layout manually. Like this

lazy var collectionView: UICollectionView = {
        let layout = CarouselFlowLayout()
        layout.scrollDirection = .horizontal
        layout.sideItemAlpha = 0.8
        layout.sideItemScale = 0.8
        layout.spacingMode = CarouselFlowLayoutSpacingMode.overlap(visibleOffset: spacing)

        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = UIColor.groupTableViewBackground
        addSubview(collectionView)
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        pinToEdges(subview: collectionView)
        return collectionView
    }()

wow-such-amazing avatar Sep 18 '18 16:09 wow-such-amazing

Yeah one thing of note is that it won't use the layout you provide programmatically. What you have to do is set up your director as a FlowCollectionDirector, and then make your layout configurations through that object. You have to give your collectionview a layout to start, so I just give it the default flow layout.

let trackListCollection: UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    let collection = UICollectionView(frame: .zero, collectionViewLayout: layout)
    collection.backgroundColor = .yellow
    collection.translatesAutoresizingMaskIntoConstraints = false
    collection.accessibilityLabel = "trackListCollection"
    return collection
}()

var trackListCollectionDirector: FlowCollectionDirector


override init(frame: CGRect) {
    self.trackListCollectionDirector = FlowCollectionDirector(self.trackListCollection)
    self.trackListCollectionDirector.minimumLineSpacing = 10
    
    self.trackListCollectionDirector.register(adapter: self.trackAdapter)
    
    self.trackListCollectionDirector.add(models: self.tracks)
    self.trackListCollectionDirector.reloadData()
    
    super.init(frame: frame)
    
    registerCells()
    setupViews()
    setupConstraints()
}

twof avatar Oct 14 '18 01:10 twof