ios - 以编程方式在 UIScrollView 中居中 subview

标签 ios swift uiview uiscrollview

我在 SO 上看到了一堆类似的问题,但没有一个能解决我的问题。

我正在添加一个 UIView 作为 UIScrollView 的 subview 。 UIView 有 3*scrollView.width 和 3*scrollView.height。因此,我相应地设置了 UIScrollViewcontentSize。当应用程序启动时,我希望 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)

最佳答案

根据我的理解,你有 UIScrollViewUIView 并且滚动内容大小是 View 高度/宽度的 3 倍,当应用程序启动时,你需要中心卷轴的。

在那种情况下,我尝试使用 Storyboard尽可能多地结束,所以我所做的,

  1. 添加了带有约束的UIScrollView

Top 空间到 SuperView,Trailing 到 SuperView,LeadingBottom 到 superView。

  1. 在带有约束的 UIScrollView 中添加了 UIView

Top 空间到 SuperView,Trailing 到 SuperView,LeadingBottom 到 superView,高度为 和宽度 等于 UIView(我们在 UIScrollView 之上) 乘以 3 倍。

这就是 Storyboard 中的所有内容,现在我们唯一需要设置的是 UIScrollViewsetContentOffset,就像这样。

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/

相关文章:

ios - 嵌套 ScrollView 与 ios 中的 TableView

ios - 使用TabViewController,保存数据时,TableView不更新

iphone - 键盘遮住了我的 UIViewController?

ios - 在 iOS 中使用 GCD 发生意外冲突

c# - 以编程方式创建按钮单点触控

iOS 忽略 enqueueSampleBuffer 因为状态失败

ios - 嵌套的 UIViews 不接收触摸事件

ios - 如何在横向模式下获取主 UIView 的宽度?

ios - 无法在强制转换中将类型 '[Record]' 的值转换为类型 'Record'

iphone - NSDateFormatter日期问题