您可以在UIView中添加集合视图吗?

时间:2020-10-14 14:17:40

标签: swift xcode uiview uicollectionview

我正在尝试在UIview中添加收藏夹视图,以显示用户帖子,例如Instagram,您可以在其中向用户个人资料左右滑动:

您可以在下面的紫色位(这是UIView)中添加收藏夹视图吗?

到目前为止,这是我尝试过的方法,但我无法使其正常工作,并且不确定要尝试什么方法

import UIKit

private let reuseIdentifier = "Cell"


class CollectionView: UIView, UICollectionViewDataSource, UICollectionViewDelegate, 
    UICollectionViewDelegateFlowLayout {


    //MARK: - Properties
    let cellId = "cellId"

    let collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let view = UICollectionView(frame: .zero, collectionViewLayout: layout)
        return view
    }()


    //MARK: - Init

    override init(frame: CGRect) {
        super.init(frame: frame)
    
        addSubview(collectionView)
        collectionView.anchor(top: topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
    
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }



    //MARK: - UICollectionView

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
    
        return cell
    }

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

    }

1 个答案:

答案 0 :(得分:1)

您需要为您的集合视图设置委托和数据源 试试这个

 lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let view = UICollectionView(frame: .zero, collectionViewLayout: layout)
view.dataSource = self 
view.delegate = self
        return view
    }()