我正在尝试将一个UICollectionView放在一个UIView内,因为我所使用的框架要求返回一个UIView。我已经查看了这个问题:如何将UICollectionView作为子视图添加到UIView中? 和 在没有故事板的情况下在UIView中添加UICollectionView ,但不确定如何使其工作。
我已经尝试过如下方法:
class TopView : UIView, UICollectionViewDataSource, UICollectionViewDelegate {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = .red
addSubview(collectionView)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
lazy var collectionView : UICollectionView = {
let layout = UICollectionViewFlowLayout()
let cv = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
cv.translatesAutoresizingMaskIntoConstraints = false
cv.delegate = self
cv.dataSource = self
cv.register(HeaderCell.self, forCellWithReuseIdentifier: "HeaderCell")
cv.backgroundColor = .yellow
return cv
}()
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HeaderCell", for: indexPath) as! HeaderCell
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: self.collectionView.frame.width, height: 200)
}
func collectionView(_ collectionView: UICollectionView, numberOfSections section: Int) -> Int {
return 1
}
}
我遇到了一个空白的屏幕。
更新:
这是我将TopView添加到UIViewController的方式:
class MainViewController: UIViewController {
var mainView = TopView()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(mainView)
}
}
我只看到一个黑屏。