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 *'
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. :)
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.
Use below code:
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
UILabel *footerLabel = [[UILabel alloc] init];
footerLabel.text = @"Centered text";
footerLabel.textAlignment = NSTextAlignmentCenter;
return footerLabel
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With