4

How can I simply scaling imageView with autolayout when scrolling down ?

Try to see parallax effect but not exactly what I wanted.

I just want to use a scrollView and a header ImageView who can resize depends on scrollView position.

casillas
  • 16,351
  • 19
  • 115
  • 215
raphael
  • 777
  • 1
  • 9
  • 18
  • Could you reformulate your question? It is very unclear what you're doing and what you want to achieve. – frp Nov 02 '15 at 16:25

1 Answers1

20

Step by Step:

1 - open storyboard and add an image view on top with these constraint (choose your aspect ratio) :

enter image description here

2 - select aspectFill mode and clipSubviews for your uiimage

3 - add a UIScrollView on top of your viewController with a child view inside. All the details about the auto layout with scrollView : http://natashatherobot.com/ios-autolayout-scrollview/

4 - then make outlets reference of your imageView and scrollView in your code.

5 - in viewDidLoad, insert self.automaticallyAdjustsScrollViewInsets = false and set contentInsets and contentOffset of the scrollView :

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 - add scrollviewDelegate to the ViewController and the scrollViewDidScroll method to get position of the scrollView

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 - then build and run.

you can download example on github: https://github.com/raphrel/scalingImageWhenScrollDown

there is maybe a better solution but this one works. enjoy

raphael
  • 777
  • 1
  • 9
  • 18