问题
Developing an iOS application with Xcode ver 9.3, Swift.
Could you tell me how to animate the height changing of a header in section of a tableview?
- A search bar is put in header in section.
- The search bar is switched to show and hide by tapping navigation bar button.(show: height of header = 44, hide: height of header = 0)
- I would like to animate when switching the search bar show and hide.
The code is as follows. The height of a header in section is immediately changed without animation...
import UIKit
class TableViewController: UITableViewController, UISearchBarDelegate {
let array = ["apple", "orange", "melon", "banana", "peach"]
let searchBar = UISearchBar()
var searchButtonTapped = false // Search bar is displayed or not
override func viewDidLoad() {
super.viewDidLoad()
searchButtonTapped = false
let searchButton = UIBarButtonItem(title: "Search", style: UIBarButtonItemStyle.plain, target: self, action: #selector(searchTapped))
self.navigationItem.leftBarButtonItem = searchButton
}
@objc func searchTapped() {
if searchButtonTapped == true {
searchButtonTapped = false
searchBar.text = nil
searchBar.resignFirstResponder()
} else {
searchButtonTapped = true
}
self.tableView.reloadData()
}
// change the height of header in section
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if searchButtonTapped == true {
return 44
} else {
return 0.1
}
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchBar.setShowsCancelButton(true, animated: true)
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.text = nil
searchBar.setShowsCancelButton(false, animated: true)
searchBar.endEditing(true)
self.tableView.reloadData()
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
searchBar.delegate = self
searchBar.placeholder = "Search..."
return searchBar
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return array.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = array[indexPath.row]
return cell
}
}
Screenshot
回答1:
self.tableView.reloadData()
is without animation.
you can try
reloadRows(at: [IndexPath], with: UITableViewRowAnimation)
or
reloadSections(sections: IndexSet, with: UITableViewRowAnimation)
来源:https://stackoverflow.com/questions/49777106/how-to-animate-the-height-changing-of-a-header-in-section-of-a-tableview