【问题标题】:get the size of UIImageView programmatically以编程方式获取 UIImageView 的大小
【发布时间】:2016-12-22 12:59:41
【问题描述】:

我正在为 iPhone 和 iPad 创建一个应用程序。现在我想在不同的手机屏幕上检索 UIImageView 的大小。我试过以下代码:

print("width \(BubbleBackground.frame.size.width)")
print("height \(BubbleBackground.frame.size.height)")
print("width1 \(BubbleBackground.bounds.size.width)")
print("height1 \(BubbleBackground.bounds.size.height)")
print("width2\(BubbleBackground.image!.size.width)")
print("height2\(BubbleBackground.image!.size.height)")

我已经尝试使用上面的代码,但无论它是在 iPhone 5、iPhone 6、iPhone 6 plus 还是 iPad 上运行,它们都会返回一个恒定值。有谁知道在不同设备上运行时如何获取图像大小?

【问题讨论】:

  • 可能是您在属性中设置了固定高度
  • 你把这段代码放在哪里?如果在viewDidLoad 中可能不正确,因为布局尚未开始
  • 不,这是纵横比,图像在 iPad 上调整为更大的分辨率,在 iPhone 上调整为小分辨率
  • 检查您是否设置了大小限制,以及是否设置了适合大小内容的设置。
  • @Tj3n 是的,你太棒了!你是对的,我不应该把它们放在 viewDidLoad 中!!非常感谢!

标签: ios iphone swift ipad uiimageview


【解决方案1】:

您必须有一些约束才能根据屏幕大小更改 imageView 框架。然后你可以在UIImageView (BubbleBackground.layoutIfNeeded()) 上使用.layoutIfNeeded() 来获取它的运行时大小。

确保您在 viewWillAppearviewDidLayoutSubviews 或这些事件之后的任何时间执行此操作。

【讨论】:

  • 是的,我发现我不应该把它们放在 viewDidLoad() 中
【解决方案2】:

您的图片在所有设备上的尺寸都相同,除非您对图片设置了限制,使其调整大小以适应当前屏幕尺寸。

约束通常使用 Xcode 的 Interface Builder 添加,但也可以通过编程方式添加。

使用 Interface Builder 添加约束 https://developer.apple.com/library/prerelease/content/documentation/UserExperience/Conceptual/AutolayoutPG/WorkingwithConstraintsinInterfaceBuidler.html#//apple_ref/doc/uid/TP40010853-CH10-SW1

以编程方式添加约束 https://developer.apple.com/library/prerelease/content/documentation/UserExperience/Conceptual/AutolayoutPG/ProgrammaticallyCreatingConstraints.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-22
    • 2016-04-25
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2012-09-03
    • 2018-09-12
    相关资源
    最近更新 更多