我想使对象框的高度为视图控制器的80%,宽度应为100%。对象框应固定在顶部,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.