Change view.frame.size.width
to a static value for y
position. Because UIView position calculation starts from Top-Left corner.
let button1 = UIButton(frame: CGRect(x: view.frame.size.width - 56, y: 20, width: 30, height: 30))
self.view.addSubview(button1)
let button12 = UIButton(frame: CGRect(x: view.frame.size.width - 56, y: 60, width: 30, height: 30))
self.view.addSubview(button12)
If you want to add AutoLayoutConstraint try this
let button1 = UIButton()
button1.setTitle("Button 1", for: .normal)
button1.backgroundColor = .red
button1.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(button1)
let button12 = UIButton()
button12.setTitle("Button 12", for: .normal)
button12.backgroundColor = .red
button12.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(button12)
button1.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: 20).isActive = true
button1.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor, constant: -20).isActive = true
button1.heightAnchor.constraint(equalToConstant: 30).isActive = true
button1.widthAnchor.constraint(equalToConstant: 100).isActive = true
button12.topAnchor.constraint(equalTo: button1.bottomAnchor, constant: 20).isActive = true
button12.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor, constant: -20).isActive = true
button12.heightAnchor.constraint(equalToConstant: 30).isActive = true
button12.widthAnchor.constraint(equalToConstant: 100).isActive = true
To know about translatesAutoresizingMaskIntoConstraints
please check it - link