Center footer UILabel in grouped UITableView – Swift

2 Solutions Collect From Internet About “Center footer UILabel in grouped UITableView – Swift”

Simply just add a footer to your tableView and it will be placed at the bottom, no matter how many sections you have

let tableViewFooter = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 50))
            tableViewFooter.backgroundColor = UIColor.greenColor()        
let version = UILabel(frame: CGRectMake(8, 15, tableView.frame.width, 30))
version.font = version.font.fontWithSize(14)
version.text = "Version 1.x"
version.textColor = UIColor.lightGrayColor()
version.textAlignment = .Center;

tableViewFooter.addSubview(version)

tableView.tableFooterView  = tableViewFooter

If you want to add a footer for each section

Create a UIView() in your tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? method and add a label to that view and center the label within it.

Example:

func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView()

        let version = UILabel(frame: CGRectMake(8, 15, tableView.frame.width, 30))
        version.font = version.font.fontWithSize(14)
        version.text = "Version 1.x"
        version.textColor = UIColor.lightGrayColor()
        version.textAlignment = .Center;

        view.addSubview(version)

        return view
    }

Hm you’re idea is well this code sample will help you to get it done properly.

- (UIView *) tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    static UIView *footerView;

    if (footerView != nil)
        return footerView;

    NSString *footerText = NSLocalizedString(@"Some Display Text Key", nil);

    // set the container width to a known value so that we can center a label in it
    // it will get resized by the tableview since we set autoresizeflags
    float footerWidth = 150.0f;
    float padding = 10.0f; // an arbitrary amount to center the label in the container

    footerView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, footerWidth, 44.0f)];
    footerView.autoresizingMask = UIViewAutoresizingFlexibleWidth;

    // create the label centered in the container, then set the appropriate autoresize mask
    UILabel *footerLabel = [[[UILabel alloc] initWithFrame:CGRectMake(padding, 0, footerWidth - 2.0f * padding, 44.0f)] autorelease];
    footerLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
    footerLabel.textAlignment = UITextAlignmentCenter;
    footerLabel.text = footerText;

    [footerView addSubview:footerLabel];

    return footerView;
}