Search code examples
swiftstoryboardconstraintsxib

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


Solution

  • 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