UILabel 获取框架的宽度或高度

UILabel get Frame width or height

`lblAddress.frame.width`
`lblAddress.frame.size.width`

我已经搜索了很多次,但我仍然没有指出...lblAddress.frame.widthlblAddress.frame.size.width 之间有什么区别。它给了我相同的输出..我不知道什么时候使用哪个?

请提供一些示例,以便我弄清楚整个事情。

它们(几乎)相同。 一个是 width of CGRect, the other one is width of CGSize.

唯一的区别是 frame.width 总是 return 正值,因为 frame.size.width 在某些情况下可能 return 负值。

如果我只关心标准化几何,我会直接使用 shorthand frame.width

框架和尺寸都有宽度属性。您可能会感到困惑,因为大小也是一个 属性 的框架。这就像我问你我穿的鞋子是什么颜色,但下一刻又问我脚穿的鞋子是什么颜色,我在问同样的事情,我可能会以一种或另一种方式问它很方便,具体取决于根据我的情况。

你想找到原点使用这个代码 这里 ViewSend 是 view

的出口
self.ViewSend.frame.origin.y

你想找到高度所以使用这个代码

self.ViewSend.frame.size.height

你想找到宽度所以使用这个代码

self.ViewSend.frame.size.width

它们几乎相同;然而,fram.width 是一个只获取值,但 frame.size.width 可用于设置或获取值

要了解更多,您可以查看CGRect结构是如何构建的。

struct CGRect {
  var origin: CGPoint
  var size: CGSize
}

为了增加一些额外的功能,Apple 还提供了 CGRect 的扩展,如下所示

extension CGRect {

    @available(iOS 2.0, *)
    public var height: CGFloat { get }

    @available(iOS 2.0, *)
    public var width: CGFloat { get }
}

现在回答你的问题。 lblAddress.frame 将 return 一个 CGRect

lblAddress.frame.width //This will use the extended functionality 
lblAddress.frame.size.width //this will use the actual struct

internally the width extension on CGRect will always use the same 
CGSize property from struct to give the width back and hence the same 
size property is accessed in both case, but the difference is the first 
one is standardized and hence only gives back positive values whereas 
the second will give the negative values as well.