【发布时间】:2017-11-13 09:39:06
【问题描述】:
我试图让 UICollectionView 位于 UIView 内,因为我使用的框架需要返回 UIView。我看过这个问题:How do I add a UICollectionView to a UIView as a subview? 和 Adding UICollectionView inside UIView without Storyboards 但不知道如何让它工作。
我尝试过这样的:
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)
}
}
我只是黑屏。
【问题讨论】:
-
布局需要设置UICollectionViewDelegateFlowLayout。
-
我已经看过了。但是我现在如何显示这个视图呢?
-
在 UIViewController 中添加正常的 UIView 并添加约束
-
我已将 UIView 嵌套在 UIViewController 中。但它返回一个空白。当我添加一个断点时,它似乎没有到达它。我还为 UIView 添加了颜色并确保该类是 TopView。 UIView 出现了,但似乎没有在课堂上。
标签: ios swift uiview uicollectionview