Dynamically restrict button to be in the lower right corner of the screen - Swift

how can I restrict the button below dynamically from the background view so that it is located in the lower right corner of the screen?

The code below is wrong, but I think I need to do something like this?

let constraints = [
            button.topAnchor.constraint(equalTo: backView.topAnchor),
            button.leftAnchor.constraint(equalTo: backView.leftAnchor, constant: -40),
            button.bottomAnchor.constraint(equalTo: backView.bottomAnchor),
            button.rightAnchor.constraint(equalTo: backView.rightAnchor, constant: -40)
        ]
        
        NSLayoutConstraint.activate(constraints)

enter image description here

Upvotes: 0

Views: 308

Answers (2)

Shehata Gamal
Shehata Gamal

Reputation: 100503

You need

NSLayoutConstraint.activate([
        button.bottomAnchor.constraint(equalTo: backView.bottomAnchor),
        button.rightAnchor.constraint(equalTo: backView.rightAnchor, constant: -20),
        button.heightAnchor.constraint(equalToConstant:30),
        button.widthAnchor.constraint(equalToConstant:30)
 ])

Upvotes: 1

Ruchi Makadia
Ruchi Makadia

Reputation: 1083

here is a code for add button lower right side of your view

        let btn = UIButton()
        btn.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(btn)
        
        btn.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -20).isActive = true
        btn.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -20).isActive = true
        btn.heightAnchor.constraint(equalToConstant: 50).isActive = true
        btn.widthAnchor.constraint(equalToConstant: 50).isActive = true

Upvotes: 2

Related Questions