Is there a way in swift to have a label and make constraints for it programmatically. For example on all devices to 'Pin to the top' or 'Pin to the right side' so that on all devices it just pins to whatever device is being used.
It's because I've created a label programmatically, so I want to make constraints for it.
If you need more info, just let me know. Thanks :)
Control-Dragging ConstraintsIf you drag more or less horizontally, you get options to set the horizontal spacing between the views, and options to vertically align the views. If you drag more or less vertically, you get options to set the vertical spacing, and options to align the views horizontally.
To create constraints select the button and click the Align icon in the auto layout menu. A popover menu will appear, check both “Horizontal in container” and “Vertically in container” options to center the button on the screen. Then click the “Add 2 Constraints” button.
addConstraint(constY); var constW:NSLayoutConstraint = NSLayoutConstraint(item: new_view, attribute: NSLayoutAttribute. Width, relatedBy: NSLayoutRelation. Equal, toItem: new_view, attribute: NSLayoutAttribute. Width, multiplier: 1, constant: 0); self.
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel()
self.view.addSubview(label)
label.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
label.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
label.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
label.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
}
This will bind the item to all the edges, making it as big as the screen. Anchor is used to refer to an point in game. which is either its superview or some view on the same level as your current view. You can use references as i did self.view.trailingAnchor
, and you can also add offsets and insets view.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 8).isActive = true
. Or you can name the direct size of something label.heightAnchor.constraint(equalToConstant: CGFloat).isActive = true
. Good luck
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With