2016-08-30 150 views
0

我有一個UIScrollView,裏面有UIImageView。只是一個簡單的測試用例:UIImageView是滾動視圖的整個寬度並且以自動佈局爲中心到Y.然而,在我的設備上的最終結果並不是真正以Y爲中心。在UIScrollView中縮放UIImageView - 不居中

但我遇到這樣的問題,即使用滾動視圖縮放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

回答

0

我不確定是否可以通過自動佈局保持居中。一種適用於我的方法是按照Apple WWDC示例中的說明將子類UIScrollView修改爲layoutSubviews。下面的代碼

-(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; 

} 
相關問題