Adding UICollectionView inside UIView without Storyboards

眉间皱痕 提交于 2019-12-04 20:46:09

You have two problems:

1) You initialise your UICollectionView incorrectly as you must give it a layout. You need something like this (use whatever frame you want but if you are going on to use auto layout it doesn't matter):

let layout = UICollectionViewFlowLayout()
let cv = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)

2) You cannot reference 'self' inside the closure when initialising a property. This is because if may not have been initialised (as in this case) so you can't guarantee it's safe to use it.

I think you should be ok if you use lazy initialisation like this (plus you don't even need to cast 'self'):

lazy var myCollectionView : UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    let cv = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
    cv.translatesAutoresizingMaskIntoConstraints = false
    cv.delegate = self
    cv.dataSource = self
    cv.backgroundColor = .yellow
    return cv
}()

Using the lazy method should delay until self is initialised and therefore safe to use.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!