你可以试试下面的代码,它工作正常。
override func viewDidLoad() {
super.viewDidLoad()
let myImageView = UIImageView()
myImageView.backgroundColor = UIColor.redColor()
self.view.addSubview(myImageView)
myImageView.translatesAutoresizingMaskIntoConstraints = false
// set contentMode to center image
myImageView.contentMode = .Center
// if you want some specific heigh and width of myImageView then uncomment below Two line to add the height & Width constraints.
// view.addConstraint(NSLayoutConstraint(item: myImageView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 200))
// view.addConstraint(NSLayoutConstraint(item: myImageView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 200))
// if you do not set the height and width constrints then myImageView size depends on actual size of image.
view.addConstraint(NSLayoutConstraint(item: myImageView, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: myImageView, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1, constant: 0))
}