Difference between frame.size.width and frame.width

后端 未结 3 1795
梦毁少年i
梦毁少年i 2020-12-17 16:15

I was writing a program in swift and just now I noticed that I can directly access a CGRect frame\'s width and height properties directly without using the

3条回答
  •  感动是毒
    2020-12-17 16:53

    In Objective C, when I tried to write the same code, the line height = view.frame.height is throwing an error. Can anyone please tell me the difference (if any) in these two lines of code.

    CGGeometry.h defines a couple of types, among them the C struct CGRect. This struct has two members: origin and size.

    That's all you can access in C (and Objective-C) using dot notation. Neither C nor Objective-C offer extensions for structs.

    Swift imports the type as a Swift struct. The difference is that Swift does allow for extensions on structs. So it exposes several free C functions as extensions:

    CGRectGetMinX() — CGRect.minX
    CGRectGetMidX() — CGRect.midX
    CGRectGetMaxX() — CGRect.maxX
    CGRectGetWidth() — CGRect.width
    [... same for y]
    

    These C functions are there since ages—they just live in a dusty corner of CoreGraphics.

    They are quite useful but you have to know their semantics (which differ a bit from the standard accessors): They normalise the dimensions.

    This means that they convert a rect with negative width or height to a rect that covers the same area with positive size and offset origin.

    let rect = CGRect(x: 0, y: 0, width: 10, height: -10)
    assert(rect.width == rect.size.width)   // OK
    assert(rect.height == rect.size.height) // boom
    

提交回复
热议问题