【发布时间】:2015-05-29 21:56:23
【问题描述】:
在这个视图控制器中,我初始化了一个UIScrollView,将其添加到层次结构中并在viewDidLoad 中添加自动布局约束,并在viewDidLayoutSubviews 中添加图像子视图。如果我将它分配给 Storyboard 中的独立视图,它会按预期运行(带有图像的方形滚动视图,我可以滚动)。但是,如果我将此视图嵌入到导航控制器中,不做任何其他更改,我会得到一个充满窗口的黑屏,没有图像。
为什么会发生这种情况,我该如何解决?我已经看到其他建议设置内容大小的问题 [1] [2]。但是,我尝试使用自动布局而不是直接设置内容大小。
这是一个最小但完整的示例。再说一遍:适用于独立视图,而不是嵌入时:
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate {
var scrollView: UIScrollView = UIScrollView(frame: CGRectZero)
override func viewDidLoad() {
super.viewDidLoad()
self.scrollView.delegate = self
self.scrollView.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.addSubview(self.scrollView)
self.scrollView.maximumZoomScale = 2
self.scrollView.minimumZoomScale = 1
self.view.setTranslatesAutoresizingMaskIntoConstraints(false)
self.configureAutolayout()
}
override func viewDidLayoutSubviews() {
if let x = UIImage(named: "photo.jpg") {
let y = UIImageView(image: x)
self.scrollView.addSubview(y)
}
}
func configureAutolayout() {
var constraint = NSLayoutConstraint(item: self.scrollView,
attribute: .Leading,
relatedBy: .Equal,
toItem: self.view,
attribute: .Leading,
multiplier: 1,
constant: 0)
self.view.addConstraint(constraint)
constraint = NSLayoutConstraint(item: self.scrollView,
attribute: .Trailing,
relatedBy: .Equal,
toItem: self.view,
attribute: .Trailing,
multiplier: 1,
constant: 0)
self.view.addConstraint(constraint)
constraint = NSLayoutConstraint(item: self.scrollView,
attribute: .Top,
relatedBy: .Equal,
toItem: self.topLayoutGuide,
attribute: .Bottom,
multiplier: 1,
constant: 0)
self.view.addConstraint(constraint)
constraint = NSLayoutConstraint(item: self.scrollView,
attribute: .Height,
relatedBy: .Equal,
toItem: self.scrollView,
attribute: .Width,
multiplier: 1,
constant: 0)
self.view.addConstraint(constraint)
}
func viewForZoomingInScrollView(scrollView: UIScrollView!) -> UIView! {
return self.scrollView.subviews.first as UIView
}
}
编辑:
删除以下行解决了一个问题并引入了另一个问题:
self.view.setTranslatesAutoresizingMaskIntoConstraints(false)
带有图像子视图的UIScrollView 现在会出现在独立视图中以及嵌入导航控制器时。但是,现在嵌入式控制器的滚动视图顶部有一个额外的、不需要的空间。我认为TopLayoutGuide 是对齐的合适视图——不是这样吗?
编辑 2:
根据这个问题 [3],通过将 self.automaticallyAdjustsScrollViewInsets 设置为 false 解决了插入问题。它的行为不符合预期。
参考资料:
[1]UIScrollView not scrolling when included into viewcontroller embedded into a navigation controller
[2]UIScrollView scroll not working after pushed with a navigation controller
【问题讨论】:
标签: ios swift uiscrollview uinavigationcontroller autolayout