ios - 以编程方式向 Swift 3 中的 ScrollView 添加约束

标签 ios swift uiscrollview

我发现我试图在设备上水平居中的 ScrollView 出现奇怪的行为。

我有一个 ScrollView ,在 viewDidLoad() 中设置

scrollView = UIScrollView()
scrollView.delegate = self
scrollView.minimumZoomScale = 0.
scrollView.maximumZoomScale = 2.0
scrollView.zoomScale = 1.0
scrollView.contentSize = CGSize(width: width, height: height) 

并且我为我的内容添加了一个 containerView。我在这里更改了背景颜色以尝试能够看到发生了什么

containerView = UIView()
containerView.backgroundColor = .black
scrollView.addSubview(containerView)
view.addSubview(scrollView)

为了对此进行测试,我决定为 containerView 设置一个前导常量(稍后我会将其居中)。

containerView.translatesAutoresizingMaskIntoConstraints = false
view.addConstraint(NSLayoutConstraint(item: containerView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 50))

View 似乎确实向右移动了 50 度。然而 1) 我丢失了 containerView 的背景颜色 2) containerView 似乎不再对手势使用react

我想我会更聪明,而是将约束添加到 scrollView - 我保留了颜色和手势,但它不会向右移动。

最佳答案

scrollView 和 View Controller View 之间的约束

 NSLayoutConstraint.activate([
            scrollView.topAnchor.constraint(equalTo: self.view.topAnchor),
            scrollView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
            scrollView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
            scrollView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor)
        ])

scrollView 和 containerView 的约束

 NSLayoutConstraint.activate([
        containerView.topAnchor.constraint(equalTo: scrollView.topAnchor),
        containerView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
        containerView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 50),
        containerView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor)
    ])

希望是有帮助的!

关于ios - 以编程方式向 Swift 3 中的 ScrollView 添加约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42743160/

相关文章:

ios - Swift - 打开/关闭时 UISwitch 不更新

ios - swift : Error when saving to core data context

arrays - 反向枚举过滤掉数组中的相似对象

ios - 如何禁用手动对角滚动同时启用对角 setContentOffset 滚动动画

ios - 我试图通过下拉 UIScrollView 来刷新一组全部放置在 UIScrollView 上的 UICollectionView

ios - 让按钮快速将文本添加到 UITextField

ios - 如何使用“查找我的 friend ”向特定 friend 开放?

ios - 声明函数在整个项目中可用

ios - HealthKit 请求授权失败

ios - 部分屏幕中的 UIScrollView