我正在关注可以平移和缩放图片的UIScrollView
上的Raywenderlich教程(https://www.raywenderlich.com/159481/uiscrollview-tutorial-getting-started)。除了我以编程方式创建视图和布局约束之外,我的代码与他们的代码完全相同。我没有工作。
我发现问题是ImageView
在bounds
中的viewDidLayoutSubviews()
值为零{}。但是,我是否在Storyboard或代码中创建了约束,这不是什么区别,对吧?如果是这样,任何建议的解决方法将不胜感激。 viewDidLoad()
中的部分是我自己的代码。
class ComposeController: UIViewController {
let scrollView = UIScrollView()
let imageView = UIImageView()
var imageViewBottomConstraint: NSLayoutConstraint!
var imageViewLeadingConstraint: NSLayoutConstraint!
var imageViewTopConstraint: NSLayoutConstraint!
var imageViewTrailingConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
imageView.image = MyImage //from Assets
scrollView.delegate = self
view.addSubview(scrollView)
scrollView.addSubview(imageView)
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
scrollView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
scrollView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
imageView.translatesAutoresizingMaskIntoConstraints = false
imageViewTopConstraint = imageView.topAnchor.constraint(equalTo: scrollView.topAnchor)
imageViewBottomConstraint = imageView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor)
imageViewLeadingConstraint = imageView.leftAnchor.constraint(equalTo: scrollView.leftAnchor)
imageViewTrailingConstraint = imageView.rightAnchor.constraint(equalTo: scrollView.rightAnchor)
imageViewTopConstraint.isActive = true
imageViewBottomConstraint.isActive = true
imageViewLeadingConstraint.isActive = true
imageViewTrailingConstraint.isActive = true
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
updateMinZoomScaleForSize(view.bounds.size)
}
fileprivate func updateMinZoomScaleForSize(_ size: CGSize) {
let widthScale = size.width / imageView.bounds.width
let heightScale = size.height / imageView.bounds.height
let minScale = min(widthScale, heightScale)
scrollView.minimumZoomScale = minScale
scrollView.zoomScale = minScale
}
}
extension ComposeController: UIScrollViewDelegate {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
}
答案 0 :(得分:1)
根据Apple的viewDidLayoutSubviews()
文档:
当视图控制器视图的边界发生变化时,视图会调整其子视图的位置,然后系统会调用此方法。但是,调用此方法并不表示已调整视图子视图的各个布局。每个子视图都负责调整自己的布局。
您可以通过调用以下方式获取视图以布置各个子视图:
self.view.setNeedsLayout()
self.view.layoutIfNeeded()