ios - 将自动布局与 UIImageView 一起使用不会保留帧大小

标签 ios swift uiimageview autolayout

我想以编程方式实现一个 UIImageView,但是当我应用自动布局约束时,它并没有像我预期的那样工作。为简单起见,我将 ImageView 的框架设置为 100 x 100。这很好用,但是一旦我添加了自动布局约束,框架大小就不再适用,图像将以全尺寸呈现(在本例中, 320px 宽)而不是缩小以适应 ImageView 框架。

这是为什么?我怎样才能获得所需的行为?我想要一个 100x100 的 ImageView ,它可以根据纵横比缩小图像,并位于屏幕中间从底部向上 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))

最佳答案

使用自动布局时不应设置任何框架。您需要为 ImageView 的宽度和高度添加两个约束。

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))

关于ios - 将自动布局与 UIImageView 一起使用不会保留帧大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26952759/

相关文章:

iOS Swift - 从 Firebase 中的日期范围查询值

objective-c - 检查条件不起作用并返回无法识别的选择器

ios - "unexpectedly found nil while unwrapping an Optional value"当我尝试通过 AVAssetImageGenerator 获取 CGImage 时

ios - 无法识别手势(双指双击): Xcode 9. 1

ios - ios 中的 Collection View 动态单元格大小

ios - 无法在 UITableViewController 中设置 TableView 的约束

ios - Firebase 电话身份验证失败

swift - 根据旋转移动 Sprite

ios - 如何在 Swift 中设置新的类文件

iphone - 如何逐步显示 UIImageView