【问题标题】:Search results disappear when tapping on search results点击搜索结果时搜索结果消失
【发布时间】:2020-12-26 10:04:12
【问题描述】:

我正在开发一个顶部有搜索栏的 UITableView(搜索栏是通过编程设置的)。我可以查看搜索结果,但是当我在搜索栏之外点击时,结果会被清除。我确信这很容易实现,但我无法弄清楚。感谢您提供任何帮助或反馈!

//
//  InventoryViewController.swift
//  ItemizePro
//
//  Created by Tyler Wasick on 5/18/20.
//  Copyright © 2020 Tyler Wasick. All rights reserved.
//

import UIKit

class InventoryViewController: UIViewController {
    
    @IBOutlet weak var inventoryTableView: UITableView!
    
    var assetList = [Asset]()
    let searchController = UISearchController(searchResultsController: nil)
    var filterAssetList = [Asset]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        // Configure the tableview delegate and data source
        inventoryTableView.delegate = self
        inventoryTableView.dataSource = self
        
        // Download asset list
        FirebaseDB.downloadAssetList { (list) in
            self.assetList = list
            self.inventoryTableView.reloadData()
        }
        
        // Setup Search Delegate
        searchController.searchResultsUpdater = self
        definesPresentationContext = true
        inventoryTableView.tableHeaderView = searchController.searchBar
        
    }
    
    // MARK: - Functions
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print(indexPath)
    }
    
    
    
    // Search bar function, looks to match name from the search to asset name
    private func filterAssets(for searchText:String) {
        filterAssetList = assetList.filter({ (asset) -> Bool in
            return (asset.name?.lowercased().contains(searchText.lowercased()))!
        })
        inventoryTableView.reloadData()
    }
    
    

}

extension InventoryViewController: UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating {
    
    func updateSearchResults(for searchController: UISearchController) {
        filterAssets(for: searchController.searchBar.text ?? "")
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        // If there is no search use the "assetList" array, if not use "filterAssetList" array
        if filterAssetList.count == 0 {
            return assetList.count
        } else {
            return filterAssetList.count
        }
         
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        // Format date field
        let formatter = DateFormatter()
        formatter.dateStyle = .medium
        formatter.timeStyle = .none
                
        // Set the cell with asset data
        let cell = tableView.dequeueReusableCell(withIdentifier: Constants.Storyboards.TableViewCell.inventoryCellID) as! InventoryListView
        
        // Get the asset for that rown
        // Initiate emtpy variable
        var cellAsset = Asset()
        if filterAssetList.count == 0 {
            cellAsset = assetList[indexPath.row]
        } else {
            cellAsset = filterAssetList[indexPath.row]
        }
        
        // Set the cell details
        cell.setInventoryCell(cellAsset)

        // Return the row
        return cell
    }
}

【问题讨论】:

  • 我认为问题出在搜索栏功能

标签: ios swift xcode uitableview uisearchbar


【解决方案1】:

我发现创建变量标志var isSearching = false 并使用它而不是 filterAssetList 计数更容易。此标志跟踪“搜索栏” 我使用本教程作为参考,它对我有很大帮助:)
https://daddycoding.com/2018/12/07/ios-tutorials-search-your-table-using-a-searchbar/

https://github.com/zhiyao92/Search-Bar

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var searchBar: UISearchBar!
    
    var data = ["Apple","Microsoft","Twitter","Facebook","Instagram"]
    var filteredData = [String]()
    var isSearching = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        searchBar.delegate = self
        tableView.dataSource = self
        searchBar.enablesReturnKeyAutomatically = false
        tableView.keyboardDismissMode = .onDrag
    }
}

extension ViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if isSearching {
            return filteredData.count
        } else {
            return data.count
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        if isSearching {
            cell.textLabel?.text = filteredData[indexPath.row]
        } else {
            cell.textLabel?.text = data[indexPath.row]
        }
        return cell
    }
}

extension ViewController: UISearchBarDelegate {
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        if searchBar.text == "" {
            isSearching = false
            tableView.reloadData()
        } else {
            isSearching = true
            filteredData = data.filter({$0.contains(searchBar.text ?? "")})
            tableView.reloadData()
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-04
    • 2020-04-08
    • 2011-08-27
    • 1970-01-01
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多