问题
I'm currently adding an information page to my app, and wish to display the version number of the app centred in the footer of a grouped UITableView. I have it displaying, but I'm not sure how to go about centring it.
I've looked at using the tableviews viewForFooterInSection; would this be the correct way going forward, or is there a simpler way?
Many thanks in advance.

回答1:
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
}
回答2:
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;
}
来源:https://stackoverflow.com/questions/34070463/center-footer-uilabel-in-grouped-uitableview-swift