Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add constraints programmatically to my UILabel

Tags:

swift

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 :)

like image 424
hus mak Avatar asked Jan 02 '18 11:01

hus mak


People also ask

How do I create a constraint in Autolayout?

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.

How do you add constraints in Xcode?

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.

How do I enable constraints in Swift?

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.


1 Answers

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

like image 95
Vollan Avatar answered Dec 12 '22 05:12

Vollan