views:

349

answers:

2

I've subclassed an UIImageView. After

self = [super initWithImage:image]

I try to access the self.frame.origin.y value. But it is always 0.0. One moment later, in a method that gets called from the outside, the property is fully there with a nice 100.0.

I also tried to override -(id)initWithFrame:(CGRect)aRect, but the result is the same. Is that property first set correctly as soon as the view is added to some superview? I belief that I am trying to get the frame rect directly after the object has been allocated and initialized, but before it gets added to the superview. That happens one line later.

+3  A: 

The frame of an object may be set at any time. If you wish to monitor for changes to the frame, override setFrame: and setBounds:

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    // Your code here
}
- (void)setBounds:(CGRect)bounds
{
    [super setBounds:bounds];
    // Your code here
}
rpetrich
Thanks. That would have been a good point to backup the original frame rectangle, but it's going to be called as soon as I do transformations like rotation. Anyway, very useful to know!
Thanks
+1  A: 

I can't reproduce this issue, but I'm having to interpolate a bit to guess where you are expecting the 100 to come from. Where are you setting it? This seems to work fine:

- (id)initWithImage:(UIImage*)image {
    self = [super initWithImage:image];
    if (self != nil)
    {
     CGRect frame = self.frame;
     frame.origin = CGPointMake(100.0, 100.0);
     self.frame = frame;
     NSLog(@"y=%d", self.frame.origin.y);
     NSLog(@"frame=%@", NSStringFromCGRect(self.frame));
    }
    return self;
}

Perhaps you could provide a bit larger piece of code?

Rob Napier
I figured out that the frame rect will not be set to anything until I added the newly allocated view to an subview. I had an data provider that created the object, added it to an array and returned it. At this point, no frame property has been set, since this is going to be done at some point later in an for-in-loop.
Thanks