如何使对象的框架高度为视图控制器的 80%

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

我想让对象框占视图控制器高度的 80%,宽度应为 100%。对象框应固定在顶部,space 的 20% 固定在底部。

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)
    }


}

如果你正在使用 iOS9+ 你可以使用 .constraint() 方法来定义 NSAutoLayoutConstraints

self.view.addSubview(box)替换为

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.