ios - UIScrollView 不滚动 - 内容大小不明确

标签 ios swift uiscrollview autolayout uikit

I am trying to create a Scroll View. The view itself is correctly displayed but it does not scroll, even though I added a view to it and set the content size.

注意:我没有使用 Storyboard ,而是仅使用约束 (AutoLayout)。

代码:

let scrollView: UIScrollView = {
        let sv = UIScrollView()
        sv.isScrollEnabled = true
        sv.backgroundColor = .brown
        return sv
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        setupViews()
    }

    func setupViews() {
        self.view.addSubview(scrollView)
        scrollView.anchor(top: self.view.topAnchor, left: self.view.leftAnchor, bottom: self.view.bottomAnchor, right: self.view.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
        scrollView.contentSize = CGSize(width: self.view.frame.width, height: 2000)

        print(scrollView.contentSize)

        let view = UIView()
        view.backgroundColor = .blue


        scrollView.addSubview(view)

        view.anchor(top: scrollView.topAnchor, left: scrollView.leftAnchor, bottom: scrollView.bottomAnchor, right: scrollView.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
    }

.anchor() 是我制作的自定义扩展,目的是使约束 View 更容易。

如有任何帮助,我们将不胜感激。

最佳答案

最好不要将自动布局与框架布局混合使用

1- 评论

scrollView.contentSize = CGSize(width: self.view.frame.width, height: 2000)

2- 在 scrollview 内的 View 与 vc 的 View 之间设置等宽约束,高度约束为 2000

为了不和vc的view change混淆

let view = UIView()

let contentView = UIView()

然后添加这两个约束

contentView.widthAnchor.constraint(equalTo:self.view.widthAnchor).isActive = true
contentView.heightAnchor.constraint(equalToConstant:2000).isActive = true

关于ios - UIScrollView 不滚动 - 内容大小不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57030840/

相关文章:

iOS:从后台线程创建 UIImage?

ios - 如何快速比较 NSDATA 字节

ios - 当搜索栏成为第一响应者时更改表 - swift

ios - 检测用户何时将手指离开 UIScrollView

ios - 如何检测 Scrollview 弹跳 - iOS

ios - KIK 无法识别 IOS 8.1.1.1

ios - 我想在不使用任何第三方框架的情况下将过滤器应用于录制的视频。我曾尝试将 CIfilter 用于 CAlayer 但它不起作用

Swift - 如何声明私有(private)嵌套结构?

ios - 快速调试器 : OS_OBJECT_HAVE_OBJC_SUPPORT = 0

swift - 存在键盘时向上移动 UITextField