I've created a navigation bar button in MainViewController
using
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Save", style: .plain, target: self, action: #selector(presentPopup))
}
@objc func presentPopup() {
let popupVC = PopupViewController()
popupVC.modalPresentationStyle = .overCurrentContext
present(popupVC, animated: true, completion: nil)
}
which presents a popup form (containing a "save" button) used for saving the main view's contents. I'd like for this "save" button (in PopupViewController
) to (1) change the title of MainViewController
's navigation bar button to "Saved" and (2) disable the button.
I have the following in PopupViewController
so far:
let popupBox: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
let button: UIButton = {
let view = UIButton()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
self.definesPresentationContext = true
view.backgroundColor = .clear
view.addSubview(popupBox)
// configure popupBox
view.addSubview(button)
// configure button
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
}
@objc func buttonAction(_ sender: UIButton) {
// save main VC's contents
// change title of main VC's nav button - WHAT GOES HERE?
// disable main VC's nav button - WHAT GOES HERE?
self.dismiss(animated: true) // dismiss popup
}
What should I add to the button's action to accomplish what I'm trying to do?
Just add a callback to PopupViewController
, that will be called in buttonAction
.
var onDismiss: (() -> Void)?
@objc func buttonAction(_ sender: UIButton) {
dismiss(animated: true)
onDismiss?()
//or, you can also run onDismiss after the dismiss animation:
// dismiss(animated: true, completion: onDismiss)
}
Assign the thing you want to do before presenting the popup:
@objc func presentPopup() {
let popupVC = PopupViewController()
popupVC.modalPresentationStyle = .overCurrentContext
popupVC.onDismiss = { [weak self] in
guard let self else { return }
self.navigationItem.title = "Saved"
self.navigationItem.rightBarButtonItem?.isEnabled = false
}
present(popupVC, animated: true, completion: nil)
}