以下是 Mete 回答的 Swift 版本:
override func viewDidLoad() {
super.viewDidLoad()
upperView.translatesAutoresizingMaskIntoConstraints = false
var constraint = NSLayoutConstraint(item: upperView,
attribute: NSLayoutAttribute.top,
relatedBy: NSLayoutRelation.equal,
toItem: self.view,
attribute: NSLayoutAttribute.top,
multiplier: 1,
constant: 0)
self.view.addConstraint(constraint)
constraint = NSLayoutConstraint(item: upperView,
attribute: NSLayoutAttribute.height,
relatedBy: NSLayoutRelation.equal,
toItem: self.view,
attribute: NSLayoutAttribute.height,
multiplier: 0.5,
constant: 0)
self.view.addConstraint(constraint)
constraint = NSLayoutConstraint(item: upperView,
attribute: NSLayoutAttribute.leading,
relatedBy: NSLayoutRelation.equal,
toItem: self.view,
attribute: NSLayoutAttribute.leading,
multiplier: 1,
constant: 0)
self.view.addConstraint(constraint)
constraint = NSLayoutConstraint(item: upperView,
attribute: NSLayoutAttribute.trailing,
relatedBy: NSLayoutRelation.equal,
toItem: self.view,
attribute: NSLayoutAttribute.trailing,
multiplier: 1,
constant: 0)
self.view.addConstraint(constraint)
}