as diu
as diu

Reputation: 1090

How to AddConstraint to a button relative to parent view's margin so that it appears 30 from top margin and 30 from right margin

This is the code I'm trying out:

    @IBOutlet weak var btnInfo: UIButton!

override func viewWillAppear(_ animated: Bool) {
    self.view.addConstraint(NSLayoutConstraint(item: self.view,
                                             attribute: .topMargin,
                                             relatedBy: .equal,
                                             toItem: btnInfo,
                                             attribute: .notAnAttribute,
                                             multiplier: 1,
                                             constant: 20))
    self.view.addConstraint(NSLayoutConstraint(item: self.view,
                                             attribute: .rightMargin,
                                             relatedBy: .equal,
                                             toItem: btnInfo,
                                             attribute: .notAnAttribute,
                                             multiplier: 1,
                                             constant: 30))
}

Trying to add .topMargin and .rightMargin constraints to get the btnInfo to appear 30 points from top and 30 from right margin. Please help.

Upvotes: 0

Views: 121

Answers (1)

AgnosticDev
AgnosticDev

Reputation: 1853

If interface builder is an option, interface builder works great for this type of functionality. Select the object you are wanting to add your margins to and set constant margins on the top and the right.

Here is a screen capture. enter image description here

Upvotes: 1

Related Questions