[英]What's the difference between UIView's frame.height and frame.size.height?
I don't understand what the difference is in a UIView
between frame.height
and frame.size.height
. 我不明白frame.height
和frame.size.height
之间的UIView
什么区别。 Why add size
? 为什么要加大size
? For example: 例如:
override func viewDidLoad() {
super.viewDidLoad()
scrollView.contentSize.height = self.view.frame.height
scrollViewHeight = scrollView.frame.size.height
}
It all started with Objective-C and CGRect
. 这一切都始于Objective-C和CGRect
。 It only has two properties - origin
and size
. 它只有两个属性 - origin
和size
。 size
is a CGSize
which in turn has a height
property. size
是一个CGSize
,后者又有一个height
属性。 So it is common in Objective-C to get the height of a frame using: 所以在Objective-C中常见的是使用以下方法获取帧的高度:
CGFloat height = frame.size.height;
Technically, the correct solution (to get a proper, normalized height) is to use: 从技术上讲,正确的解决方案(获得正确的标准化高度)是使用:
CGFloat height = CGRectGetHeight(frame);
Then Swift came along and CGRect
became a Swift struct
. 然后Swift出现了, CGRect
成了一个Swift struct
。 While it also has a size
property of type CGSize
which in turn has a height
property, the Swift CGRect
has a height
property. 虽然它还具有CGSize
类型的size
属性,而该属性又具有height
属性,但Swift CGRect
具有height
属性。 In Swift, the two lines above become: 在Swift中,上面的两行成为:
let height = frame.size.height;
and 和
let height = frame.height;
In most cases, there is no difference between the two ways to get the height of a frame. 在大多数情况下,获得帧高度的两种方法之间没有区别。 But there is a difference if the frame has a negative height. 但是如果框架具有负高度则存在差异。
Example: 例:
let rect = CGRect(x: 0, y: 0, width: 320, height: -40)
print(rect.height) // 40
print(rect.size.height) // -40
Accessing size.height
gives the raw value used when the CGRect
was created. 访问size.height
会给出创建CGRect
时使用的原始值。 Access height
gives a normalized value of the height. 访问height
给出了标准化的高度值。
In most cases you should use the height
property and not size.height
. 在大多数情况下,您应该使用height
属性而不是size.height
。 But more importantly, be consistent. 但更重要的是,要保持一致。 The code in your question is inconsistent. 您问题中的代码不一致。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.