You can do this in code, at least; I'm the type to forsake Interface Builder and go it in code anyway. IB seems to get in my way more often than not when it comes to adding or tweaking constraints. Here's what I've done in my custom UIToolbar
subclass's -initWithFrame:
method.
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
[self addSubview:self.label];
[self addConstraint:[NSLayoutConstraint
constraintWithItem:self.label
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeCenterX
multiplier:1 constant:0]];
[self addConstraint:[NSLayoutConstraint
constraintWithItem:self.label
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeCenterY
multiplier:1 constant:0]];
}
return self;
}
And since I like to lazy load as much as possible, here's my self.label
instance variable (called when [self addSubview:self.label]
gets messaged above).
- (UILabel *)label {
if (_label) return _label;
_label = [UILabel new];
_label.translatesAutoresizingMaskIntoConstraints = NO;
_label.textAlignment = NSTextAlignmentCenter;
return _label;
}
Seems to work for me. I'm not adding any UIBarButtonItems
, though, so your mileage my vary.