Can't fully scroll within UIScrollView

505 views Asked by At

I have a UIImageView within a UIScrollView, and I want to be able to scroll around the dimensions of the "regular" photo dimensions. My issue is that I am able to scroll, however when it gets to the top or towards the bottom of the photo, the scroll position does not stay, instead it "bounces" and moves back up a little bit, and does not allow for the photo to stay in that position, how would I go about fixing this?

here is the code below:

 scrollView.frame = CGRect(x: self.view.frame.width * 0, y: self.view.frame.height / 3, width: self.view.frame.width, height: self.view.frame.width)
        self.view.addSubview(scrollView)
        scrollView.delegate = self


        let image = imageView.image
        imageView.frame = CGRect(x: self.view.frame.width * 0, y: self.view.frame.height * 0, width: (image?.size.width)!, height: (image?.size.height)!)
        imageView.frame = scrollView.bounds
        imageView.contentMode = .scaleAspectFill
        scrollView.addSubview(imageView)

An example would be if you had a full screen photo taken with the camera, and then when the photo is displayed within the view, the whole photo is not able to stay in its position when it is being scrolled.

2

There are 2 answers

0
DonMag On BEST ANSWER

You are doing a number of things wrong, and as mentioned you should move to auto-layout and constraints, however...

To get your image scrolling the way you are going:

    // set scroll view frame to be full width of view, start 1/3 of the way down from the top, and make the height the same as the width
    scrollView.frame = CGRect(x: 0, y: self.view.frame.height / 3, width: self.view.frame.width, height: self.view.frame.width)

    // add the scroll view to the view
    self.view.addSubview(scrollView)

    // use "if let" so you're not force-unwrapping optionals
    if let image = imageView.image {

        // set the imageView's frame to the size of the image
        imageView.frame = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)

        // add the imageView to the scroll view
        scrollView.addSubview(imageView)

        // set the contentSize of the scroll view - the "scrollable area" - to the size of the image view
        scrollView.contentSize = imageView.bounds.size
    }
0
MandisaW On

Bouncing is an optional behavior in UIScrollView (and its subclasses, including UiTableView). You can turn it on/off via the bounces property, or in Interface Builder.

I usually bundle desired ScrollView properties together in a convenience method (or you could use UIAppearance) to ensure that all of my views have shared behavior.