我用swift 3.0寫了一個演示,並用自定義視圖包裝了UICollectionView
。延遲加載collecionView並將當前視圖設置爲數據源,但在自定義視圖擴展中會遵循UICollectionViewDataSource
直接錯誤。如何處理它?自定義視圖不符合協議UICollectionViewDataSource
代碼:
// CELLID
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
}
}
// MARK: - 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
}
}
非常感謝,我很快就使用Swift 3.0,或者不太習慣.. – RaymondWoo