我想添加一个按钮作为根视图的子视图.按钮必须水平放置在中心以及垂直于superview的中心.我以编程方式使用NSLayoutConstraints.这是我的代码.
import UIKit
class ViewController: UIViewController {
var button : UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {
button = UIButton()
button.setTitle("Hello World", forState: .Normal)
button.backgroundColor = UIColor.blueColor()
button.sizeToFit()
self.view.addSubview(button)
NSLayoutConstraint.activateConstraints([
NSLayoutConstraint(item: button, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1, constant: 0), …Run Code Online (Sandbox Code Playgroud)