I would like to record an explanation of what to do if I want to make a specific movement when I press the back button on the navigation bar.
macOS 11.0.1
Xcode version 12.2
Swift version 5.3.1
This time I would like to implement passing the value entered in TextFiled of the child screen to the parent when the back button of the Navigation bar is pressed. Pressing the back button to move from the child to the parent screen can be rephrased as pressing the back button to bring up the parent screen. When this parent screen appears, WillShow of UINavigationControllerDelegate is called. I would like to use this to control the behavior when the back button is pressed.
ChildViewController
import UIKit
//Added UINavigationControllerDelegate
class ChildViewController: UIViewController,UINavigationControllerDelegate{
@IBOutlet weak var b: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
//Write that the delegate of NavigationController is delegated by ChildViewController
navigationController?.delegate = self
}
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
//You can access the variables of ParentViewController which is the parent screen by writing the following
if let controller = viewController as? ParentViewController{
//Write what you want to process
//I want to implement this time, a will pass the text input to b which is TextFiled to the variable of the parent screen
controller.a = b.text!
}
}
}
the important thing is ** ・ UINavigationControllerDelegate when declaring class ・ NavigationController? .Delegate = self ・ Write what you want to do in willShow ** is!
Reference: When pressing the back button of navigationbar-I want to pass a value
Recommended Posts