我用swift 3.0编写了一个演示,并用自定义视图包装了一个UICollectionView
。延迟加载collecionView并将当前视图设置为数据源,但在自定义视图扩展中遵从UICollectionViewDataSource
直接错误。怎么处理?
代码:
//细胞
fileprivate let ContentCellID = "ContentCellID"
class PageContentView: UIView {
// MARK:- lazy attributes
fileprivate lazy var collecionView : UICollectionView = {
// 1.create layout
let layout = UICollectionViewFlowLayout()
layout.itemSize = self.bounds.size
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
// 2.create UICollectionView
let collecionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collecionView.showsHorizontalScrollIndicator = false
collecionView.isPagingEnabled = true
collecionView.bounces = false
collecionView.dataSource = self
// register cell
collecionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellID)
return collecionView
}()
// MARK:- define attributes
fileprivate var childVcs : [UIViewController]
fileprivate var parentVc : UIViewController
// MARK:- custom constructor
init(frame: CGRect, childVcs : [UIViewController], parentVc : UIViewController) {
self.childVcs = childVcs
self.parentVc = parentVc
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//标记:-设置用户界面
extension PageContentView {
fileprivate func setupUI() {
for childVc in childVcs {
parentVc.addChildViewController(childVc)
}
addSubview(collecionView)
collecionView.frame = bounds
}
}
//标记:-UICollectionViewDataSource
extension PageContentView : UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return childVcs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collecionView.dequeueReusableCell(withReuseIdentifier: ContentCellID, for: indexPath)
let childVc = childVcs[indexPath.row]
childVc.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVc.view)
return cell
}
}
最佳答案
您忘记实现必需的方法collectionView(_:numberOfItemsInSection:)
,请实现它。
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVcs.count
}
注意:如果您没有实现,那么您已经实现的方法
numberOfSections(in:)
是可选的方法,默认部分是1
,因此删除该方法并返回我在上面添加的childVcs.count
中的collectionView(_:numberOfItemsInSection:)
。