如何在tableview的部分中为标题的高度变化设置动画?

时间:2018-04-11 13:59:09

标签: ios swift tableview

使用Xcode ver 9.3,Swift开发iOS应用程序。

你能告诉我如何在tableview的部分中为标题的高度变化设置动画吗?

  • 搜索栏放在标题栏中。
  • 通过点击导航栏按钮切换显示和隐藏搜索栏。(显示:标题高度= 44,隐藏:标题高度= 0)
  • 我想在切换搜索栏时显示动画并隐藏。

代码如下。截面中标题的高度会立即更改而不会生成动画...

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
    }

}

截图

enter image description here

1 个答案:

答案 0 :(得分:1)

self.tableView.reloadData()没有动画。

你可以尝试

reloadRows(at: [IndexPath], with: UITableViewRowAnimation)reloadSections(sections: IndexSet, with: UITableViewRowAnimation)