我在 SO 上看到了一堆类似的问题,但没有一个能解决我的问题。
我正在添加一个 UIView
作为 UIScrollView
的 subview 。 UIView
有 3*scrollView.width 和 3*scrollView.height。因此,我相应地设置了 UIScrollView
的 contentSize
。当应用程序启动时,我希望 scrollView
窗口位于 subView
的中间,像这样 --
-------------------
| |
| ________ |
| | | |
| | | |
| ------- |
| |
-------------------
内部窗口应该是 scrollView
以及应用启动时用户看到的 UIView
部分。但是,我无法做到这一点。
scrollView
始终设置为原点 (0,0)
我这样做了-
let margins = view.layoutMarginsGuide
scrollView.leftAnchor.constraint(equalTo: margins.leftAnchor).isActive = true
scrollView.rightAnchor.constraint(equalTo: margins.rightAnchor).isActive = true
scrollView.bottomAnchor.constraint(equalTo: margins.bottomAnchor, constant: 0).isActive = true
scrollView.topAnchor.constraint(equalTo: margins.topAnchor).isActive = true
scrollView.center = self.view.center // view is the base view of which scrollView is a subview of.
subView.leftAnchor.constraint(equalTo: scrollView.leftAnchor, constant: -1*scrollView.frame.width)
subView.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: -1*scrollView.frame.height)
最佳答案
根据我的理解,你有 UIScrollView
和 UIView
并且滚动内容大小是 View 高度/宽度的 3 倍,当应用程序启动时,你需要中心卷轴的。
在那种情况下,我尝试使用 Storyboard尽可能多地结束,所以我所做的,
- 添加了带有约束的
UIScrollView
Top
空间到 SuperView,Trailing
到 SuperView,Leading
和 Bottom
到 superView。
- 在带有约束的
UIScrollView
中添加了UIView
。
Top
空间到 SuperView,Trailing
到 SuperView,Leading
和 Bottom
到 superView,高度为 和宽度
等于 UIView(我们在 UIScrollView 之上)
乘以 3 倍。
这就是 Storyboard 中的所有内容,现在我们唯一需要设置的是 UIScrollView
的 setContentOffset
,就像这样。
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let contentOffsetX = (scrollView.contentSize.width/2) - (view.bounds.width/2)
let contentOffsetY = (scrollView.contentSize.height/2) - (view.bounds.height/2)
scrollView.setContentOffset(CGPoint(x: contentOffsetX, y: contentOffsetY), animated: true)
}
我们完成了。我希望它能帮助你。 您还可以在 Github.com 找到代码库
快乐学习。
关于ios - 以编程方式在 UIScrollView 中居中 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46510357/