首页 > 解决方案 > UIScrollView 没有显示在视图中

问题描述

我正在实施UIScrollViewa CollectionViewCell。我有一个滚动视图应该显示的自定义视图,因此我在CollectionViewCell. 我以编程方式创建了所有内容,下面是我的代码:

struct ShotsCollections {
    let title: String?
}

class ShotsMainView: UICollectionViewCell {

    override init(frame: CGRect) {
        super.init(frame: frame)

        setupViews()

        containerScrollView.contentSize.width = frame.width * CGFloat(shotsData.count)

        shotsData = [ShotsCollections.init(title: "squad"), ShotsCollections.init(title: "genral")]
        var i = 0
        for data in shotsData {

            let customview = ShotsMediaView(frame: CGRect(x: containerScrollView.frame.width * CGFloat(i), y: 0, width: containerScrollView.frame.width, height: containerScrollView.frame.height))

            containerScrollView.addSubview(customview)
            i += 1
        }

    }

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

    var shotsData = [ShotsCollections]()

    var containerScrollView: UIScrollView = {
        let instance = UIScrollView()
        instance.isScrollEnabled = true
        instance.bounces = true
        instance.backgroundColor = blueColor
        return instance
    }()


    private func setupViews() { //These are constraints by using TinyConstraints
        addSubview(containerScrollView)
        containerScrollView.topToSuperview()
        containerScrollView.bottomToSuperview()
        containerScrollView.rightToSuperview()
        containerScrollView.leftToSuperview()
    }
}

现在的问题是,虽然显示了滚动视图,但其中的内容却没有。我在打印滚动视图的contentSizeframe时,它显示为 0。但是如果我检查调试视图层次结构,滚动视图包含 2 个具有特定框架的视图。

我不确定出了什么问题。任何帮助表示赞赏。

标签: iosswiftuiviewuiscrollviewuicollectionview

解决方案


当您添加customViewcontainerScrollView,您没有设置 和 之间的customView约束containerScrollView

添加这些约束,您将能够看到您customView的 s ,因为您customView有一些高度。此外,当您添加更多视图时,您需要删除最后添加的视图的底部约束,containerScrollView并为最新添加的视图创建底部约束。


推荐阅读