I am trying to achieve the following layout programmatically:
It is a subclassed UIView, on which I would like to place a UILabel with fix height (40 pixels), dynamic width (width is calculated based on the length of the text, so I guess this could be considered fix, not dynamic because I only calculate it one time), and exactly 40 pixels from the left and bottom.
Here is my code:
- (UIView *) initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
marginGeneral = 40.0f;
UILabel *titleLabel = [[UILabel alloc] init];
[titleLabel setTranslatesAutoresizingMaskIntoConstraints: NO];
titleLabel.backgroundColor = [UIColor blackColor];
titleLabel.textColor = [UIColor whiteColor];
titleLabel.text = @"Some Text";
[self addSubview:titleLabel];
NSLayoutConstraint *contsTitleLeft = [NSLayoutConstraint
constraintWithItem: titleLabel
attribute: NSLayoutAttributeLeft
relatedBy: NSLayoutRelationEqual
toItem: self
attribute: NSLayoutAttributeLeft
multiplier: 1.0
constant: marginGeneral];
NSLayoutConstraint *contsTitleRight = [NSLayoutConstraint
constraintWithItem: titleLabel
attribute: NSLayoutAttributeRight
relatedBy: NSLayoutRelationEqual
toItem: self
attribute: NSLayoutAttributeRight
multiplier: 1.0
constant: marginGeneral * -1.0f];
NSLayoutConstraint *contsTitleBottom = [NSLayoutConstraint
constraintWithItem: titleLabel
attribute: NSLayoutAttributeBottom
relatedBy: NSLayoutRelationEqual
toItem: self
attribute: NSLayoutAttributeBottom
multiplier: 1.0
constant: marginGeneral * -1.0f];
NSLayoutConstraint *contsTitleHeight = [NSLayoutConstraint
constraintWithItem: titleLabel
attribute: NSLayoutAttributeHeight
relatedBy: NSLayoutRelationEqual
toItem: nil
attribute: NSLayoutAttributeNotAnAttribute
multiplier: 1.0
constant: 40.0f];
[self addConstraints:@[contsTitleLeft, contsTitleRight, contsTitleBottom]];
[titleLabel addConstraint:contsTitleHeight];
}
return self;
}
@end
This of course gives back all kinds of constraint-related warnings and the label does not show up.
Could you nice people help me understand where did I go wrong and how to correct it? Thank you very much!
P.s.: I do not use interface builder, so that is not an option. :)
