UIImageview won't center in superview

illogic picture illogic · Nov 7, 2012 · Viewed 8.9k times · Source

I have an UIImageView which I add to a UIView to enhance the area where touches are recognized. When I try to center the UIImageView in the UIView (code below) the center is set properly but when I run the program the image is shown way off outside the frame of the UIView.

Any ideas?

// image size is 32x32 pixels but view will be created with 44x44 so touch recognition is better
self = [super initWithFrame:CGRectMake(position.x, position.y, 44, 44)];

if (self) {
    switch (color) {
        case Blue:
            self.imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pin_red"]];
            break;
        case Green:
            self.imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pin_green"]];
        default:
            break;
    }

    [self setCenter:position];
    [self addSubview:self.imageView];
    [self setExclusiveTouch:YES];        
    [self setBackgroundColor:[UIColor clearColor]];

    [self.imageView setCenter:position];

    NSLog(@"uiview center: %@", NSStringFromCGPoint(self.center));
    NSLog(@"image center: %@", NSStringFromCGPoint(self.imageView.center));

Thanks!

Answer

tillerstarr picture tillerstarr · Nov 7, 2012

The imageview setCenter is relative to its parent. Try:

[self.imageView setCenter:CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2)];