swift 我想在TableView的顶部添加搜索栏

i5desfxk  于 2023-05-05  发布在  Swift
关注(0)|答案(1)|浏览(122)

我有一个困难的时间添加一个功能搜索栏顶部我的表视图。我的代码没有它,可以很好地选择大学,但是我需要一个搜索表来过滤大学列表。
我尝试添加一个搜索栏,我发现从网上资源,但他们最终使用数组的项目列表。我的代码没有以与我在TableView中显示的项相同的格式执行此操作。如果有一种方法可以添加搜索栏,而不需要为表视图中列出的项创建数组,那就太好了。

import UIKit

class MasterViewController: UITableViewController{
        
        
    var detailViewController: DetailViewController? = nil
    var objects = [Any]()
    
    
    
    var UniName: [String] = ["The University of Texas at Austin", "Rice University", "Texas A&M University", "Baylor university", "The University of Texas at El Paso", "southern methodist university", "The University of Texas at Dallas", "Texas Tech University", "University of North Texas", "Texas A&M University-Commerce"]
    var UniAddress: [String] = ["110 Inner Campus Drive Austin, TX 78705", "6100 Main St., Houston, TX 77005-1892", "Administration Building, 400 Bizzell St, College Station, TX 77843", "1311 S 5th St, Waco, TX 76706", "500 W University Ave, El Paso, TX 79968", "6425 Boaz Lane, Dallas, TX 75205", "800 W Campbell Rd, Richardson, TX 75080", "2500 Broadway, Lubbock, TX 79409", "1155 Union Cir, Denton, TX 76203", "2200 Campbell St, Commerce, TX 75428"]
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        navigationItem.leftBarButtonItem = editButtonItem
        if let split = splitViewController {
            let controllers = split.viewControllers
            detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
        }
    }
    
    
    
    
    override func viewWillAppear(_ animated: Bool) {
        clearsSelectionOnViewWillAppear = splitViewController!.isCollapsed
        super.viewWillAppear(animated)
    }
    // MARK: - Segues
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showDetail" {
            if let indexPath = tableView.indexPathForSelectedRow {
                let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
                controller.setNewAddress(Member: UniName[indexPath.row], formap: UniAddress[indexPath.row])
                controller.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
                controller.navigationItem.leftItemsSupplementBackButton = true
            }
        }
    }
    
    // MARK: - Table View
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return UniName.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableViw.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel!.text = UniName[indexPath.row]
        return cell
    }
    
}
ippsafx7

ippsafx71#

你的问题很广泛,所以首先要做的事情。您可能应该首先从数据的模型定义开始。

// This is a model for our table
struct University {
    let name: String
    let address: String

    static let allUniversities = [
        University(name: "The University of Texas at Austin", address: "110 Inner Campus Drive Austin, TX 78705"),
        University(name: "Rice University", address: "6100 Main St., Houston, TX 77005-1892"),
        University(name: "Texas A&M University", address: "Administration Building, 400 Bizzell St, College Station, TX 77843")
        // Add more universities here
    ]
}

这将清楚地将模型与控制器逻辑分离。
自定义表的最佳方法是不使用UITablewViewController,而是在UIViewController中使用UITableView和UISearchBar。如果使用故事板,它看起来像这样:

将搜索栏添加到UITableView的顶部位置非常重要。下面是视图控制器的样子。

class ViewController: UIViewController {

    // Make sure you connect those IBOutlets to your Storyboard
    @IBOutlet var tableView: UITableView!
    @IBOutlet var searchBar: UISearchBar!

    // This is our main data source
    let data: [University] = University.allUniversities

    // This is where we save filtered results from search and display it
    var searchedResults: [University] = []

    // This is a flag that determines if to show all the results or only the searched results
    var isSearching = false {
        didSet {
            tableView.reloadData() // Reload the data if the flag changes
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        tableView.dataSource = self
        searchBar.delegate = self
    }

    // MARK: - Helper methods

    /// Retuns active dataset based on the search state
    func activeDataset() -> [University] {
        if isSearching {
            return searchedResults
        } else {
            return data
        }
    }

    /// Returns a list of univerties matching given query
    func filteredUniversities(query: String) -> [University] {
        return data.filter { $0.name.contains(query) }
    }
}

正如您在viewDidLoad方法中看到的,我们添加了ViewController作为表的dataSource和搜索栏的delegate,因此我们需要确保符合这些协议

extension ViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        let universities = activeDataset()
        let university = universities[indexPath.row] // Get data for the row

        cell.textLabel!.text = university.name // Update the cell with the data

        return cell
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1 // Our data are all in 1 section
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return activeDataset().count
    }
}

在这里,我们创建了一个逻辑来显示搜索结果或所有数据,这取决于搜索是否处于活动状态。

extension ViewController: UISearchBarDelegate {
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        // Check if the searched text has at least 1 character otherwise show all results
        guard searchText != "" else {
            isSearching = false
            searchedResults.removeAll()
            return
        }

        searchedResults = filteredUniversities(query: searchText)
        isSearching = true
    }
}

我们使用UISearchBarDelegate来确定用户何时在搜索栏中键入内容。
完整代码here

相关问题