Reputation: 897
I have my project setup like this:
I have a custom Tab Navigation Controller. In the top bar of the Custom Tab Navigation Controller is a text field. This text field changes according to the 4 main views of the app (4 tab buttons).
What I am trying to do is use the text field as a search bar by passing whatever is typed into the text field into the searchView However, I am having trouble passing the textfield.text from the Navigation Controller into searchView. I have a picture below that illustrates this more clearly.
The searchView has the search function taken care of. All I am trying to do is pass with textfieled.text value to the searchView whenever it is changed
Upvotes: 0
Views: 5590
Reputation: 2343
// global
let handleTextChangeNotification = "handleTextChangeNotification"
your FirstViewController
override func viewDidLoad() {
super.viewDidLoad()
textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
}
func textFieldDidChange(textField: UITextField){
NotificationCenter.default.post(name: NSNotification.Name(rawValue: handleTextChangeNotification), object: nil, userInfo: ["text":textField.text])
let search_screen = SearchViewController()
self.navigationController?.pushViewController(search_screen, animated: true)
}
SeacrchViewController's
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self,
selector: #selector(SeacrchViewController.handleTextChange(_:)),
name: NSNotification.Name(rawValue: handleTextChangeNotification),
object: nil)
}
func handleTextChange(_ myNot: Notification) {
if let use = myNot.userInfo {
if let text = use["text"] {
// your search with 'text' value
}
}
}
}
Upvotes: 1
Reputation: 1253
You can do something like that. In your FirstViewController
func textFieldDidChange(textField: UITextField){
let search_screen = SearchViewController()
search_screen.search_string = self.textField.text
self.navigationController?.pushViewController(search_screen, animated: true)
}
In case of storyboards
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if (segue.identifier == "Your_SearchViewController_identifier") {
let search_screen = segue.destinationViewController as!
SearchViewController
search_screen.search_string = self.textField.text
}
}
And In your SeacrchViewController's viewDidLoad:
override func viewDidLoad() {
super.viewDidLoad()
self.textField.text = self.search_string
}
Upvotes: 1