TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: TableView does not update according to search terms

Forums > Swift

@3DCDN  

I tried using a simple Strings to start to see if that would work on an array that I entered manually. That seemed to work fine. Now, if I try to use a filter on an array. I'm unable to have the tableView reflect the search terms accordingly. I have a feeling it's the way that the data is being saved but I'm unsure and how to diagnose the issue. import UIKit

class SearchViewController_TableView: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate { var data: [String] = [] //store name items here var dataEntered: [ToDoItem] = [] var filteredData: [String] = [] var barController = UISearchBar() var searching = false

@IBOutlet weak var tableVw: UITableView!
@IBOutlet weak var searchBar: UISearchBar!

// Filter does not update properly i.e. data that is filtered is not used to update table.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if searching == true {
        return filteredData.count
    } else {
        print("searchBar: Number of rows in dataEntered: \(dataEntered.count)")
        return dataEntered.count
    }
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "searchCell", for: indexPath)
    print("Contents of data:\(data)")
    //let selectedIndexPath = tableVw.indexPathForSelectedRow!
    if searching == true {
        cell.textLabel?.text = filteredData[indexPath.row]
    } else {
        cell.textLabel?.text = dataEntered[indexPath.row].name
    }

    return cell
}
override func viewDidLoad() {
    super.viewDidLoad()
    searching = false
    searchBar.searchTextField.isSelected = true
    searchBar.showsCancelButton = true
    searchBar.delegate = self
    barController.delegate = self
    navigationItem.hidesSearchBarWhenScrolling = true

    //MARK: Move data into "data"
    var instanceCount = 0
    for i in 0..<dataEntered.count {
        data.append(dataEntered[i].name)

    if dataEntered == nil {
        dataEntered[0] = ToDoItem(name: "", date: Date(), notes: "", reminderSet: false, completed: false)
        searchBar.becomeFirstResponder() // if fields are empty then open up keyboard
    }
    searchBar.becomeFirstResponder()
    // Do any additional setup after loading the view.
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    searchBar.becomeFirstResponder()
    searching = true
    // why is dataEntered not seen here?
    filteredData = data.filter({$0.lowercased().localizedCaseInsensitiveContains(searchText)})
    print("Before if statement, filteredData contains: \(filteredData)")
    for i in 0..<filteredData.count {
        if filteredData[i] == searchText.filter({$0.lowercased().localizedCaseInsensitiveContains(searchText)}) {
            // MARK: Original filter filteredData = data.filter({$0.lowercased().localizedCaseInsensitiveContains(searchText)})
            instanceCount += 1

        }

    }
    print("Filtered filteredData contents:\(filteredData)")
    if searchBar.isFirstResponder {
        print("SearchBar is first responder")
    }
    //.prefix(searchText.count) == searchText.lowercased() original search commands
    // assign search data to filteredData variable dataEntered.name.filter(...)
    tableVw.reloadData()

}
    // MARK: Search Filter

}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    searching = false
    searchBar.text = ""
    filteredData.removeAll()
    tableVw.reloadData()
    searchBar.resignFirstResponder()
    if searchBar.isFirstResponder != true {
        print("Search Bar no longer has control!!")
    }
    // clear data in dataFilter or filteredData array
    // reset data in SearchBar
}

}

2      

@3DCDN  

I figured it out myself. I had some braces missing for the cellForRowAt section which caused some issues. I also changed the logic for the numberOfRows and cellForRowAt sections to suit my needs.

2      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.