Search code examples
iosswiftuitableviewnslayoutconstraint

Centering a UILabel inside of a UITableView Header


I added my UIView as a UITableView header, but when I did, my constraints fell apart. I am trying to have my chapterVerseLabel centered inside the circle as so :

enter image description here

I accomplish this thus so far by doing this :

    var allConstraints = [NSLayoutConstraint]()
    let views = ["tableView" : tableView, "containerView" : containerView, "chapterVerseLabel" : chapterVerseLabel]
    allConstraints += NSLayoutConstraint.constraintsWithVisualFormat("V:|-70-[chapterVerseLabel]-70-|", options: [], metrics: nil, views: views)
    NSLayoutConstraint.activateConstraints(allConstraints)

But I'm not sure how to get it centered as well. It seems all my attempts to center it, don't abide by the stricter rules of centering something within a UITableView Header.

All ideas welcome.


Update

I tried adding a .CenterX value :

    let leftConstraint = NSLayoutConstraint(item: chapterVerseLabel, attribute: .CenterY, relatedBy: .Equal, toItem: containerView, attribute: .CenterY, multiplier: 1.0, constant: 0.0)
    containerView.addConstraint(leftConstraint)
    let rightConstraint = NSLayoutConstraint(item: chapterVerseLabel, attribute: .CenterX, relatedBy: .Equal, toItem: containerView, attribute: .CenterX, multiplier: 1.0, constant: 0.0)
    containerView.addConstraint(rightConstraint)

But this is the result :

enter image description here

Right now, the chapterVerseLabel sits within my containerView, which is assigned as the tableView.tableHeaderView . Like so :

tableView.tableHeaderView = containerView

Any ideas?


Solution

  • The problem with your constraint are that you have already bounded the label by giving Top and Bottom constraints. Also i dont see leading and trailing constraints You actually have to align the label vertically or horizontally or both based on your requirement.

    NSLayoutConstraint *yCS =[NSLayoutConstraint constraintWithItem:chapterVerseLabel attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:containerView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0];
    [containerView addConstraint:yCS];
    
    NSLayoutConstraint *xCS =[NSLayoutConstraint constraintWithItem:chapterVerseLabel attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:containerView attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0];
    [containerView addConstraint:xCS];
    

    Assuming containerView is your header view which gets returned from headerforView delegate method. You need to provide height and width to the label.