You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中未搜索时隐藏UITableView及搜索时移除多余行问题求助

Hey there! Let's tackle your two issues one by one—hiding the table view initially and getting rid of those extra rows in your search results.


1. Hide UITableView Initially & Toggle Visibility Properly

First, let's make sure the table view stays hidden until a search is initiated. Here's what to adjust:

Step 1: Set Initial Hidden State

Add this to your viewDidLoad to hide the table view right when the screen loads:

override func viewDidLoad() {
    super.viewDidLoad()
    // Hide the table view initially
    searchTableView.isHidden = true
    // Don't forget to set up delegates
    searchTextField.delegate = self
    searchTableView.dataSource = self
    searchTableView.delegate = self
}

Step 2: Update Visibility Based on Search Input

Fix your filterText function to show/hide the table view based on whether there are search results, and handle empty search input correctly:

func filterText(_ query: String){
    searchedArray.removeAll()
    
    // Only filter if the query isn't empty
    if !query.isEmpty {
        for str in LocationData {
            if str.lowercased().starts(with: query.lowercased()){
                searchedArray.append(str)
            }
        }
    }
    
    // Show table view only if there are search results
    searchTableView.isHidden = searchedArray.isEmpty
    searchTableView.reloadData()
}

Step 3: Fix Text Field Text Calculation

Your original shouldChangeCharactersIn method had a bug when deleting text—let's correct how we calculate the updated search text:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    guard let currentText = textField.text else { return true }
    // Correctly compute the updated text after the edit
    let updatedText = (currentText as NSString).replacingCharacters(in: range, with: string)
    
    filterText(updatedText)
    return true
}

2. Eliminate Extra Rows in UITableView

The extra rows are caused by inconsistent logic in numberOfRowsInSection. Let's simplify this by removing the confusing filtered variable and basing row count directly on search state:

Update Row Count Logic

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // Only return rows if there's active search text and results
    guard let searchText = searchTextField.text, !searchText.isEmpty else {
        return 0
    }
    return searchedArray.count
}

Simplify Cell Configuration

Since we now only show the table view when there are valid search results, you can clean up cellForRowAt:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.textLabel?.text = searchedArray[indexPath.row]
    return cell
}

Bonus: Hide Table After Selecting a Result

Make sure to hide the table view and dismiss the keyboard when a user selects a location:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    searchTextField.text = searchedArray[indexPath.row]
    searchTableView.isHidden = true
    searchTextField.resignFirstResponder() // Hide keyboard
}

With these changes, your table view will stay hidden until a user types a search query with matching results, and you won't see any extra rows cluttering the table.

内容的提问来源于stack exchange,提问作者gul Ranaa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 23:07:32