首页 > 解决方案 > 如何在collectionViewCell中使用动态大小的scrollView

问题描述

我想创建这个页面。我在 viewController 中创建了一个 collectionView。但是我怎样才能使这个动态的高度,我认为我需要创建一个滚动视图?如何更改集合视图大小而不是加载的 json 数据?而这个页面的结构应该如何?

我以编程方式创建了集合视图,但我现在没有任何数据。但是当我创建集合视图时,我必须给出高度值。我必须在加载 json 数据时设置框架详细信息。请帮助这个主题..至少请注意..谢谢大家

编辑:

我在单元格内添加了滚动视图,但现在无法在单元格之间切换。在红色区域(单元格)工作切换但不适用于 containerView..

滚动视图问题

class NewsDetailController: UIViewController {

private lazy var collectionView: UICollectionView = {
    let frame = CGRect(x: 0, y: 100, width: view.frame.width, height: 800)
    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .horizontal
    
    let cv = UICollectionView(frame: frame, collectionViewLayout: layout)
    cv.isPagingEnabled = true
    cv.delegate = self
    cv.dataSource = self
    cv.showsHorizontalScrollIndicator = false
    cv.register(NewsDetailCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    return cv
}()

// MARK: - Lifecycle

override func viewDidLoad() {
    super.viewDidLoad()
    configureUI()
    
}
// MARK: - Helpers

func configureUI() {

    view.addSubview(collectionView)
    view.backgroundColor = .white
    
    view.addSubview(stackBottomButtons)
    stackBottomButtons.anchor(left: view.leftAnchor,bottom: view.bottomAnchor,right: view.rightAnchor,paddingLeft: 16,paddingBottom: 32,paddingRight: 16, height: 60)
    backButton.widthAnchor.constraint(equalToConstant: 100).isActive = true
    shareButton.widthAnchor.constraint(equalToConstant: 100).isActive = true
    
}

 }

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

    return cell
}

}

extension NewsDetailController: UICollectionViewDelegateFlowLayout {


func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: view.frame.width, height: 800)
}
}

class NewsDetailCell: UICollectionViewCell {

// MARK: - Properties

let contentLabel: UILabel = {
    let label = UILabel(frame: CGRect.zero)
    label.numberOfLines = 0
    return label
}()

// MARK: - Lifecycle

override init(frame: CGRect) {
    super.init(frame: frame)
    configure()
    configureUI()
}

func configure() {
    contentLabel.text = articleViewModel?.article.content
}

func configureUI() {

    addSubview(contentLabel)
    contentLabel.anchor(top: stack.bottomAnchor,left: leftAnchor,right: rightAnchor)

}

}

我想做这个页面。

完整代码

标签: swiftuicollectionviewuiscrollview

解决方案


我想你正在寻找这样的东西

要使帧大小动态化,您需要通过单元格内的属性组合高度来设置单元格大小,这可以在您使用此链接创建的 customCell 文件中完成


推荐阅读