Hello, I was facing the challenge on the Project 7, the one with filtering petitions and i thought it'd be cool to put a "home" button on the navigation bar, that put all petitions in the table view after they were filtered. It's working fine if the button sits there all the time - I just add this to navigationItem.leftBarButtonItems array after view is loaded.
Although, when all the petitions are already shown, there no point for this button to exist.
It could be added to the leftBarButtonItems array during the app is running, but it doesn't appear there just like that - is there any method to reload navigation bar?
Here's my viewDidLoad method with the solution I tried (didn't work):
override func viewDidLoad() {
super.viewDidLoad()
let urlString: String
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .bookmarks, target: self, action: #selector(showCredits))
let home = UIBarButtonItem(title: "Home", style: .plain, target: self, action: #selector(loadHomeView))
let filter = UIBarButtonItem(barButtonSystemItem: .search, target: self, action: #selector(filterPetitions))
navigationItem.leftBarButtonItems = [filter]
if navigationController?.tabBarItem.tag == 0 {
urlString = "https://www.hackingwithswift.com/samples/petitions-1.json"
} else {
urlString = "https://www.hackingwithswift.com/samples/petitions-2.json"
}
if let url = URL(string: urlString) {
if let data = try? Data(contentsOf: url) {
parse(json: data)
return
}
}
showError()
if petitions.count != originalPetitions.count {
navigationItem.leftBarButtonItems?.insert(home, at: 0)
}
}
There are two arrays of petitions, since I decided to store the data from JSON as the "originalPetitions" and "petitions" as the array to show in tableview. The "loadHomeView" method assign originalPetitions to petitions and reload tableview, the "filterPetitions" assign filtered petitions to petitions array - it's working fine.