Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center align UITableViewCell's footer

How could I center align UITableViewCell's footer?

I've tried using the following code but it does not work:

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
    UILabel *footerLabel = [[UILabel alloc] init];
    footerLabel.text = @"Centered text";
    footerLabel.textAlignment = NSTextAlignmentCenter;
    return footerLabel.text;
}

I have also tried creating a UIView but I get an Incompatible pointer types returning 'UIView *' from a function with result type 'NSString *'

like image 859
alvarolopez Avatar asked Jul 31 '14 12:07

alvarolopez


4 Answers

Swift 3:

override func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
    let footer: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
    footer.textLabel?.textAlignment = .center
}

Worked like a charm. :)

like image 58
Riajur Rahman Avatar answered Oct 20 '22 19:10

Riajur Rahman


This code will center footer text:

- (void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section
{
    UITableViewHeaderFooterView *footer = (UITableViewHeaderFooterView *)view;
    footer.textLabel.textAlignment = NSTextAlignmentCenter;
}

It will match existing UITableView footer styles, and also handles device rotation and different widths properly without needing to mess with frames or constraints.

like image 34
jt314 Avatar answered Oct 20 '22 19:10

jt314


Use below code:

    - (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
UILabel *footerLabel = [[UILabel alloc] init];
    footerLabel.text = @"Centered text";
    footerLabel.textAlignment = NSTextAlignmentCenter;
return footerLabel
}
like image 35
Dhawal Dawar Avatar answered Oct 20 '22 18:10

Dhawal Dawar


Swift 2/3/4+ one line safe solution:

override func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
    (view as? UITableViewHeaderFooterView)?.textLabel?.textAlignment = .center
}
like image 2
Federico Zanetello Avatar answered Oct 20 '22 20:10

Federico Zanetello