Search code examples
swiftimageviewheightframesubview

How to make frame height of object 80 percent of view controller


I want to make the object box 80 percent height of the view controller and the width should be a 100 percent. The object box should be pinned to the top with the 20 percent of space being pinned to the bottom.

import UIKit

class ViewController: UIViewController {
    
    var box = UIImageView()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        box.backgroundColor = .blue
        
        
        box.frame = self.view.frame
        
        self.view.addSubview(box)
    }


}

Solution

  • Provided you are using iOS9+ you can use the .constraint() methods to define NSAutoLayoutConstraints

    Replace self.view.addSubview(box) with

    box.translatesAutoresizingMaskIntoConstraints = false
    self.view.addSubview(box)
    
    // equal width
    box.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true
    // centered X-axis (horizontally)
    box.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
    
    // Equal height with a 0.8 (80%) scaling factor aka multiplier
    box.heightAnchor.constraint(equalTo: self.view.heightAnchor, multiplier: 0.8).isActive = true
    
    // Pinned to the top
    box.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
    
    // No bottom is needed as we have a set height and set top anchor.