繁体   English   中英

以编程方式获取UIImageView的大小

[英]get the size of UIImageView programmatically

我正在为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上运行,它们都为我返回了一个恒定值。 有谁知道在不同设备上运行时如何获取图像大小?

除非您在图像上设置了约束以使其调整大小以适合当前屏幕尺寸,否则图像在所有设备上的尺寸均相同。

约束通常是使用Xcode的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

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

请确保您在viewWillAppearviewDidLayoutSubviews或在这些事件发生后的任何时候执行此操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM