UICollectionView 高度不能在 UIScrollView 内部动态增加

sal*_*lih 5 scroll uiscrollview ios uicollectionview swift

我正在开发一个为用户显示照片的应用程序。我的设计就像 Pinterest 应用程序。我添加了UICollectionViewinsideUIScrollView和 disabledUICollectionView的滚动。但是当我使用这个 UICollectionView 这样的组件时,根据其内容不可滚动。只有可见显示,其他不显示。这个项目的主要痛点是 CollectionViews 的内容是动态的。它可以随着用户交互而改变。我的问题是如何使用 UIScrollView 完全滚动 UICollectionView 及其动态内容。

让我分享截图。

第一张图片描述了第一次打开。第二张图片描述了滚动问题。第三张图片描述了我的故事板。

谢谢你的帮助。

这是我的故事板

还有我的代码

//
//  ViewController.swift
//  ScrollCollectionView
//
//  Created by Cbs on 31.05.2017.
//  Copyright © 2017 Cbs. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    @IBOutlet weak var collectionView: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 25
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
        cell.addShadow(opacitiy: 1, shadowRadius: 3, shadowOffsetWidth: 2, shadowOffsetHeight: 2, shadowColor: UIColor.lightGray, backgroundColor: UIColor.red)
        cell.addCornerRadius(cornerRadius: 8)
        return cell

    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let cellSpacing = CGFloat(2) //Define the space between each cell
        let leftRightMargin = CGFloat(40) //If defined in Interface Builder for "Section Insets"
        let numColumns = CGFloat(2) //The total number of columns you want

        let totalCellSpace = cellSpacing * (numColumns - 1)
        let screenWidth = UIScreen.main.bounds.width
        let width = (screenWidth - leftRightMargin - totalCellSpace) / numColumns
        let height = CGFloat(210) //whatever height you want

        return CGSize(width: width, height: height) // width & height are the same to make a square cell
    }

}
Run Code Online (Sandbox Code Playgroud)

编辑:

我想我无法清楚地解释我的问题。在这里,我将提供一些额外的视频来清楚地说明这个问题。我上传了 2 个视频。

在这个视频中,我的标题没有随着 collectionview 的孩子滚动。所以我想在屏幕中滚动整个元素。( https://youtu.be/0ArQe6mZytc )

在这个短视频中,您可以看到滚动时 Pinterest 应用程序的行为。我想让我的应用程序像这个视频(https://youtu.be/Nm-sjXVEL5s

小智 2

采用 NSLayoutConstraint 作为集合视图的高度,并在 viewdidLayoutSubviews() 方法中更改该高度约束,如下所示。 self.hgtCollectionView.constant = CGFloat(number of rows) * 210) + CGFloat(10)

这将根据其内容更新集合视图的高度。