When you know the exact dimensions you want to set for your label, you can initialize a UILabel
with a CGRect
frame.
let frame = CGRect(x: 0, y: 0, width: 200, height: 21)
let label = UILabel(frame: frame)
view.addSubview(label)
CGRect frame = CGRectMake(0, 0, 200, 21);
UILabel *label = [[UILabel alloc] initWithFrame:frame];
[view addSubview:label];
You can add constraints on a UILabel
when you want iOS to dynamically calculate its frame at runtime.
let label = UILabel()
label.backgroundColor = .red
label.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(label)
NSLayoutConstraint.activate([
//stick the top of the label to the top of its superview: label.topAnchor.constraint(equalTo: view.topAnchor)
//stick the left of the label to the left of its superview //if the alphabet is left-to-right, or to the right of its //superview if the alphabet is right-to-left: label.leadingAnchor.constraint(equalTo: view.leadingAnchor)
//stick the label’s bottom to the bottom of its superview: label.bottomAnchor.constraint(equalTo: view.bottomAnchor)
//the label’s width should be equal to 100 points: label.widthAnchor.constraint(equalToConstant: 100)
])
UILabel *label = [[UILabel alloc] init];
UILabel *label = [UILabel new]; label.translatesAutoresizingMaskIntoConstraints = NO; [self.view addSubview label]; // add horizontal constraints with 5 left and right padding from the leading and trailing