Gold challenge - CGRect confusion


#1

I was having a hard time with the gold challenge - my hat icon class’s drawRect method was never being called. After cheating and looking at the answer in the sample code download, I found out why, but I don’t really understand it.

It turns out that this will work:

hat = [[HypnosisterHat alloc] initWithFrame:CGRectMake(0,0, 100, 100)]; [view addSubview:hat];

And so will this:

CGRect hatPos = CGRectMake(0, 0, 100, 100); hat = [[HypnosisterHat alloc] initWithFrame:hatPos]; [view addSubview:hat];

But originally in my code, I was doing something like this, and it simply wasn’t working.

CGRect hatPos; hatPos.origin.x = 0; hatPos.origin.y = 0; hatPos.size.width = 100; hatPos.size.width = 100; hat = [[HypnosisterHat alloc] initWithFrame:hatPos]; [view addSubview:hat];

Now I can see that using CGRectMake is more elegant anyway, but that aside, why does building the CGRect “manually” like this cause drawRect to never be called? Is the end result hatPos actually any different from one built using CGRectMake?


#2
  CGRect hatPos;
  hatPos.origin.x = 0;
  hatPos.origin.y = 0;
  hatPos.size.width = 100;
  hatPos.size.width = 100;
  hat = [[HypnosisterHat alloc] initWithFrame:hatPos];
  [view addSubview:hat];

You had a zero-height rectangle - You meant to set the height but instead set the width twice.

Set up your rect like this:

  CGRect hatPos;
  hatPos.origin.x = 0;
  hatPos.origin.y = 0;
  hatPos.size.height = 100;
  hatPos.size.width = 100;
  hat = [[HypnosisterHat alloc] initWithFrame:hatPos];
  [view addSubview:hat];

Or like this:

  CGRect hatPos = {{0, 0}, {100, 100}};
  hat = [[HypnosisterHat alloc] initWithFrame:hatPos];
  [view addSubview:hat];

#3

Oh yes, of course. What a dumb mistake. Thanks.