CGRectMake alternative
Asked Answered
I

3

6

I have seen this alternative to using CGRectMake() in order to initialise a CGRect variable:

CGRect frame = (CGRect){0,0,10,10};

My question is, how does CGRect frame = (CGRect){0,0,10,10}; work? What's going on behind the scenes? It looks like a c-style array is being initialised ({x,y,w,h}) which is then being cast as a CGRect struct - is this correct? If so, how is it possible to cast a c style array as a struct?

N.B. I am not asking if it is appropriate to use the above alternative to CGRectMake(), I only wish to understand why/how it works.

Ingold answered 7/8, 2012 at 8:45 Comment(1)
It simply works if the two statements create the same sequence of bytes. However, I am confused that you are using 0 and 10 instead of 0.0 and 10.0. 0 and 10 would be compiled as integer constants and 0.0 and 10.0 would be come out als float/double constants. Tehrefore I doubt that you could use float as a legal frame for anything useful. CGRect is a stucture made of CGPoint and CGSize. Both of them are made of two CGFload members (x and y in the case of CGPoint and width and height in the case of CGSize).Autocratic
S
8

It's a so-called compound literal. You can read more about them in this article by Mike Ash: Friday Q&A 2011-02-18: Compound Literals.

Span answered 7/8, 2012 at 9:3 Comment(0)
W
1

U can use like this:

CGRect rect = CGRectFromString(@"{{0, 0}, {612, 892}}"); // it contents { CGPoint origin;CGSize size;};
NSLog(@"rect : %@",NSStringFromCGRect(rect));
Wystand answered 7/8, 2012 at 9:1 Comment(0)
M
1

Check this:

CGPoint origin = {10, 20};
CGSize size = {100, 200};
CGRect rect = {origin, size};
Mckenney answered 9/9, 2013 at 9:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.