在UIView里面添加UICollectionView而不用Storyboard

我有ViewController调用myVC与UITablewView – myTable

我想要的是从代码中添加一些UIView作为myTable的 headerView。 所以在myVC的 viewDidLoad()方法里面我加了这个代码

let topView = TopView() topView.frame.size.height = 100 topView.frame.size.width = myTable.frame.width myTable.tableHeaderView = featuredEventsView 

我也创build了一个名为TopView.swift的文件

 class TopView : UIView { override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = .red } required init?(coder aDecoder: NSCoder) {.....} } 

它正在工作,因为它应该。 我在myTable的headerView中看到红色的UIView。

现在我想在topView中添加UICollectionView,我在这里有问题。 我正在尝试做类似的事情

 class TopView : UIView, UICollectionViewDataSource, UICollectionViewDelegate { override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = .red addSubview(myCollectionView) } required init?(coder aDecoder: NSCoder) {.....} let myCollectionView : UICollectionView = { let cv = UICollectionView() cv.translatesAutoresizingMaskIntoConstraints = false cv.delegate = self as! UICollectionViewDelegate cv.dataSource = self as! UICollectionViewDataSource cv.backgroundColor = .yellow return cv }() } 

我还创build了UICollectionViewDataSource所需的function,但是应用程序在构build后崩溃。 我究竟做错了什么?

你有两个问题:

1)你不正确地初始化你的UICollectionView,因为你必须给它一个布局。 你需要像这样的东西(使用任何你想要的框架,但如果你要使用自动布局,这并不重要):

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

2)初始化属性时,不能在闭包内引用“自我”。 这是因为如果可能没有被初始化(在这种情况下),所以你不能保证使用它是安全的。

我认为你应该可以,如果你使用这样的懒惰初始化(加上你甚至不需要投“自我”):

 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 }() 

使用懒惰的方法应该延迟,直到自我初始化,因此安全使用。