以某种方式未呈现集合视图。 我之前有一个类似的问题UICollectionView not getting rendered 但是这个与弱引用有关,下面的代码没有弱引用,但仍然没有任何东西被渲染。
import UIKit
class ViewController: UIViewController {
private let cellReuseIdentifier = "collectionCell"
let scrollerView = ScrollerView()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(scrollerView)
}
}
class ScrollerView:UIView, UICollectionViewDataSource {
let leftAndRightPaddings: CGFloat = 80.0
let numberOfItemsPerRow: CGFloat = 7.0
let screenSize: CGRect = UIScreen.main.bounds
private let cellReuseIdentifier = "collectionCell"
var items = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
let flowLayout:UICollectionViewFlowLayout
let collectionView:UICollectionView
init() {
flowLayout = UICollectionViewFlowLayout()
collectionView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
super.init(frame:.zero)
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellReuseIdentifier)
collectionView.dataSource = self
collectionView.backgroundColor = UIColor.cyan
self.addSubview(collectionView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return self.items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellReuseIdentifier, for: indexPath)
cell.backgroundColor = UIColor.green
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
let width = (screenSize.width-leftAndRightPaddings)/numberOfItemsPerRow
return CGSize(width: width, height: width)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
{
return UIEdgeInsets(top: 20, left: 8, bottom: 5, right: 8)
}
}