微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ios – 是否可以在UIScrollView中放大和缩小UIImageView,但坚持使用自动布局?

长话短说,我正在尝试构建类似于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

如何使用自动布局进行缩放工作?

解决方法

使用Autolayout时,对setFrames的调用没有生效,这就是为什么imageView不在scrollView中居中.

话虽这么说,为了达到中心效果,你可以选择:

>最简单的方法是在ViewDidLoad中为您的imageView设置translatesAutoresizingMaskIntoConstraints为YES,它会将对setFrame:的调用转换为基于imageView autoresizingMask的新约束.但是您应确保新约束满足您设置的约束在你的故事板中(在你的情况下没有).
>在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]];

原文地址:https://www.jb51.cc/iOS/333585.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐