【问题标题】:UILabel get Frame width or heightUILabel 获取框架宽度或高度
【发布时间】:2017-06-06 03:38:22
【问题描述】:
`lblAddress.frame.width`
`lblAddress.frame.size.width`

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

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

【问题讨论】:

    标签: swift cgrect cgsize


    【解决方案1】:

    它们(几乎)是一样的。 一个是width of CGRect,另一个是width of CGSize

    唯一的区别是frame.width 将始终返回正值,因为frame.size.width 在某些情况下可能返回负值。

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

    【讨论】:

      【解决方案2】:

      frame 和 size 都有一个 width 属性。您可能会感到困惑,因为尺寸也是框架的属性。就像我问你我穿什么颜色的鞋子,但下一刻问我的脚穿什么颜色的鞋子,我问的是同样的事情,我可能会方便地问一种或另一种方式根据我的情况。

      【讨论】:

        【解决方案3】:

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

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

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

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

        现在回答你的问题。 lblAddress.frame 将返回一个 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.
        

        【讨论】:

          【解决方案4】:

          你想找到原点使用这个代码 这里 ViewSend 是视图的出口

          self.ViewSend.frame.origin.y
          

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

          self.ViewSend.frame.size.height
          

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

          self.ViewSend.frame.size.width
          

          【讨论】:

            【解决方案5】:

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

            【讨论】:

              猜你喜欢
              • 2015-03-15
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2017-12-26
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多