在UIScrollView中缩放UIImageView - 不居中

时间:2016-08-30 14:34:23

标签: ios swift uiscrollview uiimageview zoom

我有一个带有UIImageView的UIScrollView。只是一个简单的测试用例:UIImageView是滚动视图的全宽,并以自动布局为中心。但是,在我的设备上的最终结果中,它并没有真正以Y为中心。

但我遇到的问题是,当使用滚动视图缩放UIImageView时,它会漂移"到底部区域 - 不仅仅是应该在中心缩放。它也是"漂移"缩小时(在视频的最末端)向左反弹并反弹回中心。

我制作了一个关于此行为的小预览视频:https://www.youtube.com/watch?v=ivRNkzNrcEA

这是我的简单测试代码:

class TestController: UIViewController, UIScrollViewDelegate {

@IBOutlet weak var SCROLL: UIScrollView!
@IBOutlet weak var IMAGE: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    SCROLL.minimumZoomScale = 1;
    SCROLL.maximumZoomScale = 6.0;
    SCROLL.zoomScale = 1.0;
    SCROLL.contentSize = IMAGE.frame.size;
    SCROLL.delegate = self;


}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
}

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

}

func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
    return IMAGE
}

func scrollViewDidZoom(scrollView: UIScrollView) {

}

func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {

}

}

这是我的测试自动布局:

enter image description here

1 个答案:

答案 0 :(得分:0)

我不确定是否可以仅使用自动布局来保持居中。一种适合我的方法是子类UIScrollView并修改layoutSubviews,如Apple WWDC示例中所示。代码

-(void) layoutSubviews
{
    [super layoutSubviews];
    UIImageView *v = (UIImageView *)[self.delegate viewForZoomingInScrollView:self];
    //Centering code

    CGFloat svw = self.bounds.size.width;
    CGFloat svh = self.bounds.size.height;
    CGFloat vw = v.frame.size.width;
    CGFloat vh = v.frame.size.height;

    CGRect f = v.frame;

    if (svw > vw)
    {
        f.origin.x = (svw - vw)/2.0;
    }
    else
    {
        f.origin.x = 0;
    }

    if (svh > vh)
    {
        f.origin.y = (svh - vh)/2.0;
    }
    else
    {
        f.origin.y = 0;
    }

    v.frame = f;

}