2015-11-02 64 views
2

滚动时,我如何简单地缩放imageViewautolayoutImageView向下滚动时缩放

尝试看到视差效果,但不完全是我想要的。

我只想用一个scrollView和头ImageView谁可以调整大小取决于scrollView位置。

+0

你能重新表达你的问题吗?目前还不清楚你在做什么以及你想达到什么。 – frp

回答

17

步骤通过步骤:

1 - 开放故事板并与这些约束添加在顶部的图像视图(选择您长宽比):

enter image description here

2 - 选择aspectFill模式和clipSubviews为你的uiimage

3 - 在里面有一个子视图的viewController的顶部添加一个UIScrollView。有关scrollView的自动布局的所有细节:http://natashatherobot.com/ios-autolayout-scrollview/

4 - 然后在您的代码中使您的imageView和scrollView的插座引用。

5 - 在viewDidLoad中,插入 self.automaticallyAdjustsScrollViewInsets =假,并设置contentInsets和滚动视图的contentOffset:

class ViewController: UIViewController { 

    @IBOutlet weak var scrollView: UIScrollView! 
    @IBOutlet weak var imageView: UIImageView! 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     self.automaticallyAdjustsScrollViewInsets = false 
    } 

    override func viewDidLayoutSubviews() { 
     super.viewDidLayoutSubviews() 

     let imageHeight = imageView.frame.height 

     let newOrigin = CGPoint(x: 0, y: -imageHeight) 

     scrollView.contentOffset = newOrigin 
     scrollView.contentInset = UIEdgeInsets(top: imageHeight, left: 0, bottom: 0, right: 0) 
    } 

} 

6 - 添加scrollviewDelegate到ViewController和scrollViewDidScroll方法来获取滚动视图

的位置
class ViewController: UIViewController, UIScrollViewDelegate 

override func viewDidLoad() { 
     super.viewDidLoad() 

     scrollView.delegate = self 
     self.automaticallyAdjustsScrollViewInsets = false 
} 

func scrollViewDidScroll(scrollView: UIScrollView) { 

    let offsetY = scrollView.contentOffset.y 

    if offsetY < 0 
    { 
     imageView.frame.size.height = -offsetY 
    } 
    else 
    { 
     imageView.frame.size.height = imageView.frame.height 
    } 
} 

7 - 然后建立并运行。

你可以在github下载例如: https://github.com/raphrel/scalingImageWhenScrollDown

有可能是更好的解决方案,但是这一个工程。 享受