我正在使用 UIImageView
, Content Mode 设置为 Aspect Fit . UIImageView
正确调整了我的图像大小,但即使没有设置约束,它也不会在调整大小后更改自己的帧 .
我需要什么:
-
我需要
UIImageView
根据图像内部调整自己的帧大小 . 我在Storyboard配置了图像视图 . -
我需要在视图中再次布局其他对象,因为UIImageView的大小已更改 .
我尝试过的:
我创造了:
-
UIViewController(白色背景)→UIImageView(灰色背景)→里面的示例图像 .
-
约束:前导和尾随约束设置为零,Y约束设置为垂直对齐UIImageView .
正如您在正确缩放图像后看到的那样,UIImageView的框架仍然具有不正确的尺寸(灰色背景) .
我试图手动设置UIImageView大小:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let newSize = AVMakeRect(aspectRatio: backgroundImageView.image!.size, insideRect: backgroundImageView.frame)
backgroundImageView.frame = newSize
}
在该示例代码中,我计算了图像大小并将帧大小设置为图像的大小 . 我不知道它是否更好,所以我不需要使用AVFoundation的方法 .
问题:其他对象放置不正确,因为UIImageView的大小已更改且约束现在无效 .
这些方法对我不起作用:
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
即使我将在 viewDidLayoutSubviews()
调用我的UIImageView大小计算其他约束仍然使用旧的UIImageView的大小 .
问题
-
如何更改UIImageView 's size correctly? Maybe I can do it without code? Maybe I need to play with Hugging/Compression? I'已尝试过但没有运气 .
-
如何强制查看 recalculate other constraints 所以他们将使用新的UIImageView大小?例如,我可以在UIImageView的顶部放置红色方块,但是在通过我的方法调整UIImageView之后,红色方块仍将处于旧的UIImageView的位置 .