gpt4 book ai didi

ios - 旋转时图像尺寸发生变化

转载 作者:搜寻专家 更新时间:2023-11-01 06:30:29 24 4
gpt4 key购买 nike

我有一个名为 sampleImage 的图像,我试图沿 xy 轴 拉伸(stretch)它,如下所示landscape 它根本不起作用

 override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator)
{
if (UIDevice.current.orientation == UIDeviceOrientation.portrait)
{
sampleImage.frame = CGRect(x: 0, y: 0, width: 220, height: 120)
}
else
{
sampleImage.frame = CGRect(x: 0.2, y: 0.2, width: 220, height: 120)
}
}

然后,我在viewDidLayoutSubviews()中做了如下操作,

override func viewDidLayoutSubviews() {

super.viewDidLayoutSubviews()

if (UIDevice.current.orientation == UIDeviceOrientation.portrait)
{
sampleImage.frame = CGRect(x: 0, y: 0, width: 220, height: 120)
}
else
{
sampleImage.frame = CGRect(x: 0.2, y: 0.2, width: 220, height: 120)
}
}

如果设备处于landscape,这会起作用,但是一旦你将它旋转到portrait并返回,所有的变化都消失了。如何确保这些尺寸保持不变旋转时也一样吗?

最佳答案

基本上,都是关于 constraints 的.解决问题的第一种方法是处理设备旋转 ( good so answer ) 并通过 setNeedsUpdateConstraints 方法 ( another good so answer ) 手动更改它。这种方式适用于具有 UI 和约束的复杂更改的大屏幕。在您的情况下,您最好根据可以在 Storyboard 中设置的设备方向使用特定常量进行约束。

所以,请按照以下步骤操作:

UIImageView 设置 Equal HeightsEqual Widths 约束,然后双击 Width Equals: 120约束:

enter image description here

打开 View as: iPhone ... 底栏:

enter image description here

在右侧选择特定的设备和横向,然后在右侧面板的 Constant 之前点击 +

enter image description here

它会根据所选的设备和方向自动设置正确的宽度高度,因此您只需要为这种情况输入常量。运行项目并查看结果。

肖像:

enter image description here

横向:

enter image description here

请注意,也不要忘记不同的设备可能具有不同的尺寸类别(紧凑型 x 紧凑型、紧凑型 x 常规型等),因此您可能需要添加更多常量来处理此问题 ( see the table at the bottom of the article ) .

最后,您通过使用 Storyboard而非编程方式解决了问题。这样做的优点 - 你的代码不会长大,也不会对 UI 的事情负责,缺点 - 你应该将 constant 添加到你想要使用的每个尺寸类中。

关于ios - 旋转时图像尺寸发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48112176/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com