Dou*_*ith 8 objective-c uiscrollview uiimageview ios autolayout
长话短说,我正在尝试构建类似于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;
}
Run Code Online (Sandbox Code Playgroud)
但是使用自动布局它根本就没有.
我对UIScrollView或UIImageView没有任何限制,因为我不知道它们应该是什么.我想我应该将UIScrollView粘贴到四个角落,但是对于UIImageView我不完全确定,因为缩放改变了它的框架.
这是一个示例项目:http://cl.ly/21371H3q381N
如何使用自动布局进行缩放工作?
使用自动布局时,对 setFrames 的调用不会生效,这就是为什么 imageView 不在滚动视图中居中的原因。
话虽这么说,为了达到中心效果,您可以选择:
最简单的方法是为您的 imageView 设置为translatesAutoresizingMaskIntoConstraints
,这将根据您的 imageView autoresizingMask将调用转换为新的约束。但是您应该确保新的约束满足您在故事板中设置的约束(在您的情况下没有)。YES
ViewDidLoad
setFrame:
在您的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]];
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1101 次 |
最近记录: |