I've done something similar in my app - not exactly what you are looking for, but should give you enough to go on:
func setupNavBar() {
let rightButton = UIButton()
rightButton.setTitle("Leave", for: .normal)
rightButton.addTarget(self, action: #selector(rightButtonTapped(button:)), for: .touchUpInside)
navigationController?.navigationBar.addSubview(rightButton)
rightButton.tag = 97
rightButton.frame = CGRect(x: self.view.frame.width, y: 0, width: 120, height: 20)
let targetView = self.navigationController?.navigationBar
let trailingConstraint = NSLayoutConstraint(item: rightButton, attribute:
.trailingMargin, relatedBy: .equal, toItem: targetView,
attribute: .trailingMargin, multiplier: 1.0, constant: -16)
let bottomConstraint = NSLayoutConstraint(item: rightButton, attribute: .bottom, relatedBy: .equal,
toItem: targetView, attribute: .bottom, multiplier: 1.0, constant: -6)
rightButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([trailingConstraint, bottomConstraint])
}

I also created this function to remove it (hence the tag use above):
func removeRightButton(){
guard let subviews = self.navigationController?.navigationBar.subviews else{
log.info("Attempt to remove right button but subviews don't exist")
return
}
for view in subviews{
if view.tag == 97 {
view.removeFromSuperview()
}
}
}