Search code examples
objective-cuitabbarcontrolleruilabelcenter

Centering objects within UITableViewController


I have two views in a UITabbarController with tableViews that are centered perfectly using this code

float origenX = [self locationTable].contentSize.width * .1;
float origenY = ([[self view] frame].size.height / 2) - ([self        locationTable].contentSize.height / 2);
float sizeW = [self locationTable].contentSize.width * .8;
float sizeH = [self locationTable].contentSize.height;
CGRect newFrame = CGRectMake(origenX, origenY, sizeW, sizeH);

[[self locationTable] setFrame:newFrame];

but in another view in the same viewController I have a label and try to space it the same way

float labelW = [[UIScreen mainScreen] bounds].size.width * .8;
float labelH = [[UIScreen mainScreen] bounds].size.height * .6;
float x = ([[UIScreen mainScreen] bounds].size.width / 2) - (labelW / 2);
float y = ([[UIScreen mainScreen] bounds].size.height / 2) - (labelH / 2);

[[self infoLabel] setFrame:CGRectMake(x, y, labelW, labelH)];

Only the label is not centered correctly on the Y axis. I have tried centered by getting sizes using

[[UIScreen mainScree] bounds].height /  2
[[self view] superView] bounds].height / 2
[[self view] bounds].height / 2

Any ideas? Why can I easily center it with a tableView but not a label? Thanks


Solution

  • Why dont you make use of

    CGRectInset
    Returns a rectangle that is smaller or larger than the source rectangle, with the same center point.
    

    For example:

    UIView *baseView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 100,100)];
    [baseView setBackgroundColor:[UIColor blackColor]];
    UIView *innerView = [[UIView alloc] initWithFrame:CGRectInset(baseView.bounds, 20, 20)];
    [innerView setBackgroundColor:[UIColor grayColor]];
    NSLog(@"%@",NSStringFromCGRect(baseView.bounds));
    NSLog(@"%@",NSStringFromCGRect(baseView.frame));
    NSLog(@"%@",NSStringFromCGRect(CGRectInset(baseView.bounds, 8, 8)));
    [baseView addSubview:innerView];
    [self.view addSubview:baseView];
    

    UILabel inherits from UIView so you can make user of -setCenter: method to set the centerpoint