Search code examples
iosswiftuiscrollviewuiimagescale

How to scale UIImage to fit dimensions of UIScrollView?


I have a UIImage of dimensions 300x600 (height x width). UIImage's relative hierarchy is like so :

enter image description here

Using AutoLayout, I have set the following constraints for the UIImageView, UIScrollView and UIVIew:

enter image description here

I have set relative height dimensions of the TableView as follows:

// Setting Last Row to height = 70 pixels and first row to fill balance of screen:
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    if indexPath.row == 1 { return 70 }
    else { return tableView.frame.size.height - 70 }
}

What I would like is for the height of the UIImage to exactly match the height of the UISCrollView that it sits in. I am not concerned about the eventual width of the UIImage, but would like it to follow confines of 'AspectFit'. So I would probably employ

imageView.contentMode = UIViewContentMode.ScaleAspectFit

... probably in

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
}

I would set the dynamic height and width parameters of the UIScrollView, and then set the UIImage height to follow the height of the UISCrollView and allow the ScaleAspectFitto automatically handle the width.

I have tried various renditions of code to achieve this, but have failed to achieve the desired result.

Question: Am I on the right track? Can anyone kindly get me started with some skeleton code so I can customise it to my needs.

Side Note: I am only allowing for portrait mode of my app. No landscape.

Many thanks in advance for your kind attention and time ;)


Solution

  • I would make a container UIView to hold the exact UIScrollView then I can create constraints of scroll view's child UIImageView to that of the container view i.e. equal heights.

    As I suppose, these constraints are to their parents like

    UIView <--> UIScrollView <--> UIImageView 
    

    but try them as

    UIView <--> UIImageView