UIScrollView contentLayoutGuide和缩放居中

时间:2017-09-02 02:49:45

标签: uiscrollview zoom ios11

这里要解决的问题是如何在保持居中的同时放大UIScrollView。如果您不采取某些预防措施,默认情况是,当我们缩小时,缩放视图会向上滑动到滚动视图的左上角,如下所示:

enter image description here

那么如何防止这种情况,并在缩放时将缩放视图保持在中心?正如你可能知道的那样,传统的方法是通过弄乱滚动视图的布局来解决这个问题,正如Josh和Eliza在精彩经典WWDC video 104 from 2010中描述的那样。这可以通过使用委托或通过子类化UIScrollView来完成,并提供所需的结果:

enter image description here

现在出现了WWDC 2017视频201(https://developer.apple.com/videos/play/wwdc2017/201/?time=1496),并且有一个声称新的(iOS 11)contentLayoutGuide解决了缩放问题,同时以新的方式保持中心:她说将内容视图居中放在内容布局指南的中心。

但她不演示。当我为自己尝试时,我发现它并没有解决问题。我正在 缩放,但是当缩放 out 时,缩放比例小于1时,内容视图会向上移动到左上角,就像它一样永远都有。

有没有人弄清楚视频中的这个主张究竟意味着什么? iOS 11如何使中心变焦比过去更容易?

编辑我实际上收到了Apple的一个示例项目,以回应我的错误报告,他们声称如何解决这个问题,并没有!所以我得出结论,即便是苹果也不知道他们在这里谈论什么。

2 个答案:

答案 0 :(得分:-3)

视图位于左上角,因为未定义滚动视图的contentSize。在iOS 11中使用新的自动布局指南时,仍然需要定义contentSize。

添加以下约束:

scrollView.contentLayoutGuide.widthAnchor.constraint(equalTo: scrollView.frameLayoutGuide.widthAnchor),
scrollView.contentLayoutGuide.heightAnchor.constraint(equalTo: scrollView.frameLayoutGuide.heightAnchor)

当我有一个具有固定宽度/高度的contentView以及以下附加约束时,这对我有用:

//  give the centerView explicit height and width constraints
centerView.widthAnchor.constraint(equalToConstant: 500),
centerView.heightAnchor.constraint(equalToConstant: 500),

//  pin the center of the centerView to the center of the scrollView's contentLayoutGuide
centerView.centerXAnchor.constraint(equalTo: scrollView.contentLayoutGuide.centerXAnchor),
centerView.centerYAnchor.constraint(equalTo: scrollView.contentLayoutGuide.centerYAnchor)

答案 1 :(得分:-3)

这是您/每个人都在寻找的解决方案。在我的情况下,我想在视图滚动视图中居中一个视图。因此,如果表视图滚动,则自定义视图将始终位于滚动视图内容的中心。

// create a view
let v:UIView = UIView(frame:CGRect.zero)    // use zero if using constraints
    ibTableView.addSubview(v)
    ibTableView.bringSubview(toFront:v)
v.translatesAutoresizingMaskIntoConstraints = no
v.backgroundColor = .yellow
v.widthAnchor.constraint(equalToConstant:100).isActive = yes
v.heightAnchor.constraint(equalToConstant:100).isActive = yes

// set scrollview guides
ibTableView.contentLayoutGuide.widthAnchor.constraint(equalTo:ibTableView.frameLayoutGuide.widthAnchor).isActive = yes
ibTableView.contentLayoutGuide.heightAnchor.constraint(equalTo:ibTableView.frameLayoutGuide.heightAnchor).isActive = yes

// anchor view
v.centerXAnchor.constraint(equalTo:ibTableView.contentLayoutGuide.centerXAnchor).isActive = yes
v.centerYAnchor.constraint(equalTo:ibTableView.contentLayoutGuide.centerYAnchor).isActive = yes