iOS tip: Center UILabel in tableFooterView

If you’re building an app that supports portrait and landscape you will probably run into an issue with keeping things centered after device rotation. Below is a quick example of adding a UILabel to a UITableView’s footer and keeping it centered regardless of device rotation. The trick is to use autoresizingMask which does all the magic for you. 😉

    //create the uiview container
    UIView *tfooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _tableView.frame.size.width, 45)];
    tfooterView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    //create the uilabel for the text
    UILabel *label3 = [[UILabel alloc] initWithFrame:CGRectMake(_tableView.frame.size.width/2-120, 0, 240, 35)];
    label3.backgroundColor = [UIColor clearColor];
    label3.font = [UIFont systemFontOfSize:12];
    label3.numberOfLines = 2;
    label3.lineBreakMode = UILineBreakModeWordWrap;
    label3.textAlignment = UITextAlignmentCenter;
    label3.text = @"Some text you want centered in your tableFooterView.";
    label3.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin;
    //add the label to the view
    [tfooterView addSubview:label3];
    //add the view to the uitableview footer
    _tableView.tableFooterView = tfooterView;

, , ,