Create a new UITableViewCell for the header. Add your autolayout contraints. Then use in ViewController.

TrackHeaderCell.h

#import <UIKit/UIKit.h>

@interface TrackHeaderCell : UITableViewCell
@property (strong, nonatomic) UILabel *titleLabel;
@end

TrackHeaderCell.m

#import "TrackHeaderCell.h"

@interface TrackHeaderCell()

@end

@implementation TrackHeaderCell

#pragma mark - Creation and Layout

- (instancetype) init
{
    self = [super init];
    if (!self) return self;

    [self setupTitleLabel];

    return self;
}

- (void) updateConstraints
{
    [self addViewConstraints];
    [super updateConstraints];
}

- (void)addViewConstraints
{
    NSLayoutConstraint *centerY = [NSLayoutConstraint constraintWithItem:self.titleLabel
                                                               attribute:NSLayoutAttributeCenterY
                                                               relatedBy:NSLayoutRelationEqual
                                                                  toItem:self.contentView
                                                               attribute:NSLayoutAttributeCenterY
                                                              multiplier:1
                                                                constant:0];

    NSLayoutConstraint *centerX = [NSLayoutConstraint constraintWithItem:self.titleLabel
                                                               attribute:NSLayoutAttributeCenterX
                                                               relatedBy:NSLayoutRelationEqual
                                                                  toItem:self.contentView
                                                               attribute:NSLayoutAttributeCenterX
                                                              multiplier:1
                                                                constant:0];

    NSArray<NSLayoutConstraint *> *constraints = @[centerX, centerY];

    [NSLayoutConstraint activateConstraints:constraints];
}

- (void)setupTitleLabel
{
    self.titleLabel = [UILabel new];
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;

    [self.contentView addSubview:self.titleLabel];
}

@end

ViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];

    TrackHeaderCell *tableHeaderView = [TrackHeaderCell new];
    tableHeaderView.titleLabel.text = @"Results";
    self.tableView.tableHeaderView = tableHeaderView;
}

Screen Shot 2017-06-14 at 6.11.21 AM.png

Advertisement