使用UIImageView的自动布局不会保留帧大小

Jor*_*n H 1 uiimageview ios autolayout swift

我想以UIImageView编程方式实现,但是当我应用自动布局约束时,它不能像我预期的那样工作.为简单起见,我将图像视图的帧设置为100 x 100.这很有效,但是一旦我添加自动布局约束,帧大小就不再受到尊重,图像将以其完整大小呈现(在这种情况下) ,320px宽)而不是缩小以适应图像视图框架.

为什么这样,我怎样才能获得所需的行为?我想要一个100x100的图像视图,它可以根据纵横比缩小图像,并且位于屏幕中间居中的底部50.

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))
Run Code Online (Sandbox Code Playgroud)

rde*_*mar 6

使用自动布局时,不应设置任何帧.您需要为图像视图的宽度和高度添加两个约束.

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))
Run Code Online (Sandbox Code Playgroud)