Вам необходимо установить это свойство вашей кнопки, которое заставляет вас добавлять ограничения программным способом:
settingsButton.translatesAutoresizingMaskIntoConstraints = false
Это мой код:
func setupNav() {
guard let navController = navigationController else { return }
let navBar = navController.navigationBar
let button = UIButton()
button.setTitle("Test", for: .normal)
button.setTitleColor(.red, for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(self, action: #selector(openSettings), for: .touchUpInside)
navBar.addSubview(button)
navBar.addConstraints([
NSLayoutConstraint(item: navBar, attribute: .trailing, relatedBy: .equal, toItem: button, attribute: .trailing, multiplier: 1, constant: 20),
NSLayoutConstraint(item: button, attribute: .centerY, relatedBy: .equal, toItem: navBar, attribute: .centerY, multiplier: 1, constant: 0)
])
}
Happy кодирование.