长话短说,我正在尝试构建类似于 Photos.app 的功能。
我有一个 UIScrollView,其中有一个 UIImageView 设置在 Storyboard 中。缩放可以工作,但我无法使其保持居中。在我所有基于框架的滚动视图实现中,我将其居中如下,效果非常好:
- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
CGRect newImageViewFrame = self.imageView.frame;
// Center horizontally
if (newImageViewFrame.size.width < CGRectGetWidth(scrollView.bounds)) {
newImageViewFrame.origin.x = (CGRectGetWidth(scrollView.bounds) - CGRectGetWidth(self.imageView.frame)) / 2;
}
else {
newImageViewFrame.origin.x = 0;
}
// Center vertically
if (newImageViewFrame.size.height < CGRectGetHeight(scrollView.bounds)) {
newImageViewFrame.origin.y = (CGRectGetHeight(scrollView.bounds) - CGRectGetHeight(self.imageView.frame)) / 2;
}
else {
newImageViewFrame.origin.y = 0;
}
self.imageView.frame = newImageViewFrame;
}
但使用自动布局则完全不是这样。
我对 UIScrollView 或 UIImageView 没有任何限制,因为我不知道它们应该是什么。我想我应该将 UIScrollView 粘合到四个角,但对于 UIImageView 我不完全确定,因为缩放会改变其框架。
这是一个示例项目:http://cl.ly/21371H3q381N http://cl.ly/21371H3q381N
我将如何通过自动布局进行缩放和居中工作?
使用自动布局时,对 setFrames 的调用不会生效,这就是为什么 imageView 不在滚动视图中居中的原因。
话虽这么说,为了达到中心效果,您可以选择:
最简单的方法是设置translatesAutoresizingMaskIntoConstraints
to YES
为您的图像查看ViewDidLoad
,这会将调用转换为setFrame:
基于您的 imageView 的新约束自动调整大小蒙版 https://stackoverflow.com/questions/10370140/setautoresizingmask-from-code-in-osx。但是您应该确保新的约束满足您在故事板中设置的约束(在您的情况下没有)。
In your scrollViewDidZoom:
方法直接添加约束以使 imageView 居中
-
[self.imageView addConstraint:[NSLayoutConstraint constraintWithItem:self.imageView
attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual
toItem:self.scrollView attribute:NSLayoutAttributeCenterX multiplier:1.0
constant:0]];
[self.imageView addConstraint:[NSLayoutConstraint constraintWithItem:self.imageView
attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual
toItem:self.scrollView attribute:NSLayoutAttributeCenterX multiplier:1.0
constant:0]];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)