Zeebok
Zeebok

Reputation: 388

ChildView didn't maintain its ParentView Frame

Hope all of you will be fine. Guys i have a situation, I have a uiview and uibutton as under:

UIView* containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 200, self.view.frame.size.width, 70)];
    containerView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:containerView];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.backgroundColor = [UIColor redColor];
    [button addTarget:self action:@selector(SettingPressed:) forControlEvents:UIControlEventTouchUpInside];
    UIImage *image = [UIImage imageNamed:@"settings_button.png"];
    [button setImage:image forState:UIControlStateHighlighted & UIControlStateNormal & UIControlStateSelected];
    
    button.frame = CGRectMake(0,0, 40, 40);
    button.center = containerView.center;
    [containerView addSubview:button];

The problem is uibutton appear far from uiview instead of in the middle of uiview. What i am mistaking, please guide me. Thanks.

Upvotes: 1

Views: 23

Answers (1)

giorashc
giorashc

Reputation: 13713

First, when you change a view's center property the frame property will be changed automatically so you only should set the button center:

button.center = CGPointMake(containerView.frame.size.width  / 2, 
                              containerView.frame.size.height / 2);

Now, whenever you change the center property you need to manually tell the view to redraw itself using setNeedsDisplay :

[button setNeedsDisplay]

and lastly, the difference between frame and bounds that frame defines the position and size relative to the parent view while bounds describes the drawing area inside (or outside) the frame.

Upvotes: 1

Related Questions