gpt4 book ai didi

swift - 自定义 View 不符合协议(protocol) UICollectionViewDataSource

转载 作者:行者123 更新时间:2023-11-28 15:59:18 25 4
gpt4 key购买 nike

我用 swift 3.0 编写了一个演示,并用自定义 View 包装了一个 UICollectionView。延迟加载collecionView并将当前 View 设置为数据源,但在自定义 View 扩展中遵守UICollectionViewDataSource直接报错。如何处理?

代码:

//小区ID

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

//MARK:- 设置 UI

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

enter image description here

最佳答案

您忘记实现所需的方法 collectionView(_:numberOfItemsInSection:),实现它。

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVcs.count
}

注意:方法numberOfSections(in:)如果你没有实现默认部分是 1,那么你实现的是可选方法,所以删除该方法并在 collectionView(_ :numberOfItemsInSection:) 我在上面添加的。

关于swift - 自定义 View 不符合协议(protocol) UICollectionViewDataSource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41310751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com