Reputation: 55865
I would like to implement a UIImageView
programmatically but it's not working quite like I expected when I apply auto layout constraints. For simplicity, I've set the frame of the image view to be 100 x 100. This works well, but once I add auto layout constraints the frame size is no longer respected and the image is rendered at its full size (in this case, 320px wide) instead of scaling down to fit within the image view frame.
Why is that and how can I obtain the desired behavior? I wanted a 100x100 image view that would scale the image down respecting the aspect ratio, and located 50 up from the bottom centered in the middle of the screen.
let imageView = UIImageView(frame: CGRectMake(0, 0, 100, 100))
imageView.image = UIImage(named: "myimg")
imageView.contentMode = .ScaleAspectFit
imageView.clipsToBounds = true
imageView.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.addSubview(imageView)
self.view.addConstraint(NSLayoutConstraint(item: imageView, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 1, constant: -50))
self.view.addConstraint(NSLayoutConstraint(item: imageView, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1, constant: 0))
Upvotes: 1
Views: 3191
Reputation: 104092
You should not set any frames when using auto layout. You need to add two more constraints for the width and height of the image view.
let imageView = UIImageView()
// your other code here
imageView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 100))
imageView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 100))
Upvotes: 7