在tableView中的UITableViewHeaderFooterView中垂直居中textLabel:willDisplayHeaderView:forSection:

Gla*_*vid 4 iphone objective-c uitableview ios

我试图垂直居中tableViewHeader的文本标签.这是相关的代码- (void) tableView: (UITableView*) tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section:

- (void) tableView: (UITableView*) tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    if(![view isKindOfClass:[UITableViewHeaderFooterView class]]){
        return;
    }

    UITableViewHeaderFooterView *tableViewHeaderFooterView = (UITableViewHeaderFooterView *) view;
    UILabel* label = tableViewHeaderFooterView.textLabel;

    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont rev_lightAppFontOfSize: 24.0f];
    label.textColor = [UIColor rev_colorWithHex: 0x858585];
    label.text = [label.text capitalizedString];

    label.center = tableViewHeaderFooterView.center; // label not in superview yet

    tableViewHeaderFooterView.layer.borderColor = [UIColor greenColor].CGColor;
    tableViewHeaderFooterView.layer.borderWidth = 2.0f;

    tableViewHeaderFooterView.contentView.layer.borderColor = [UIColor purpleColor].CGColor;
    tableViewHeaderFooterView.contentView.layer.borderWidth = 2.0f;

    label.layer.borderColor = [UIColor orangeColor].CGColor;
    label.layer.borderWidth = 2.0f;

}
Run Code Online (Sandbox Code Playgroud)

label对象不是tableViewHeaderFooterView的子视图,因此居中代码似乎不起作用.有什么想法吗?

Gla*_*vid 13

好吧,我最终搞清楚如何做到这一点.不幸的是你无法在tableView:willDisplayHeader:function中处理垂直居中,因为tableViewHeaderFooterView在幕后做了一些棘手的tableView.因此,我发现最好的方法是在您自己的标题视图中返回一个标签.相关代码在这里:

- (UIView*) tableView: (UITableView*) tableView viewForHeaderInSection: (NSInteger)  section
{
    UIView* view = [[UIView alloc] init];
    UILabel* label = [[UILabel alloc] init];

    label.text = [self tableView: tableView titleForHeaderInSection: section];
    label.textAlignment = NSTextAlignmentCenter;

    [label sizeToFit];
    label.translatesAutoresizingMaskIntoConstraints = NO;

    [view addSubview:label];

    [view addConstraints:
     @[[NSLayoutConstraint constraintWithItem:label
                                  attribute:NSLayoutAttributeCenterX
                                  relatedBy:NSLayoutRelationEqual
                                     toItem:view
                                  attribute:NSLayoutAttributeCenterX
                                 multiplier:1 constant:0],
     [NSLayoutConstraint constraintWithItem:label
                                  attribute:NSLayoutAttributeCenterY
                                  relatedBy:NSLayoutRelationEqual
                                     toItem:view
                                  attribute:NSLayoutAttributeCenterY
                                 multiplier:1 constant:0]]];

    return view;
}
Run Code Online (Sandbox Code Playgroud)

希望这会帮助其他人!

干杯