UIScrollView contentLayoutGuide和缩放居中

mat*_*att 11 zoom uiscrollview ios11

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

在此输入图像描述

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

在此输入图像描述

现在到2017年的WWDC视频201(https://developer.apple.com/videos/play/wwdc2017/201/?time=1496),并有伊丽莎作出要求,新(iOS版11)contentLayoutGuide解决了放大,而问题以新的方式保持中心:她说将内容视图置于内容布局指南的中心.

但她没有证明.当我为自己尝试时,我发现它并没有解决问题.我缩放就好了,但变焦时出来,使变焦倍数小于1,内容画面上移至左上角,只是因为它总是有.

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

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

IMc*_*D23 -3

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

添加以下约束:

scrollView.contentLayoutGuide.widthAnchor.constraint(equalTo: scrollView.frameLayoutGuide.widthAnchor),
scrollView.contentLayoutGuide.heightAnchor.constraint(equalTo: scrollView.frameLayoutGuide.heightAnchor)
Run Code Online (Sandbox Code Playgroud)

当我有一个具有固定宽度/高度和以下附加约束的 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)
Run Code Online (Sandbox Code Playgroud)