Making the SearchBar retrieve accurate data in swift - swift

So far Ive gotten my searchbar to work with my firebase Firestore App, but for some reason my searchbar is not retrieving data accurately. Because, no matter what text I type in the search bar, the tableview presents the same item as my search results.
Im using Cloud Firestore as my database, but I don't think that that's the issue for why my search is posting the same item as the search result.
extension ProductListController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchBar.text != "" {
return self.productInventory.count
}
return productSetup.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "ProductListCell") as?
ProductListCell else { return UITableViewCell() }
//search not empty
if searchBar.text != "" {
cell.configure(withProduct: productInventory[indexPath.row])
}
cell.configure(withProduct: productSetup[indexPath.row])
return cell
}
}
I've looked through multiple questions on stack and seems like the answers I'm getting are not much help. Hopefully someone here can help me figure this out and solve my issue.

I think problem is in cellForRowAt:- Try This
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "ProductListCell") as?
ProductListCell else { return UITableViewCell() }
//search not empty
if searchBar.text != "" {
cell.configure(withProduct: productInventory[indexPath.row])
}else{
cell.configure(withProduct: productSetup[indexPath.row])
}
return cell
}

Related

How to change editing style for specific cell in tableview

I have a tableview where the editingstyle is .delete for all the cells. But I want to have some specific cells that doesnt have editingstyle (so that you can't swipe them, .none). Anyone have any suggestions for how to implement this?
I tried to write something like UITableViewCell.EditingStyle.none for that specific row but that didnt work.
Thanks in advance, Pontus
Consider the following example:
class ViewController: UITableViewController {
private let arr = (1...10).map { "Item \($0)" }
override func viewDidLoad() {
super.viewDidLoad()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arr.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
cell?.textLabel?.text = arr[indexPath.row]
return cell ?? UITableViewCell()
}
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
if indexPath.row == 2 {//<- Your condition
return .none
} else {
return .delete
}
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
}
So the key is to use editingStyleForRowAt in order to change the style for a specific cell (or even multiple cells) (see the documentation for further reference: https://developer.apple.com/documentation/uikit/uitableviewdelegate/1614869-tableview).

UISearchController: indexPath doesn't change with original array

It's easier to explain by example. I have original array which is searched and filtered array with searched items. If i found one item after searching and tap on it, i mark it as done (I have todo list), but when i cancel my search, I find that the first element in the original array is marked, not the third item.
I googled some threads and found almost similar problems, but solutions doesn't suit to my problem. For example:
didSelectRowAtIndexPath indexpath after filter UISearchController - Swift
And here some code. Especially at didSelectRowAt I mark the items to done. Does anyone have any ideas?
private var searchBarIsEmpty: Bool {
guard let text = searchController.searchBar.text else { return false }
return text.isEmpty
}
private var isFiltering: Bool {
return searchController.isActive && !searchBarIsEmpty
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if isFiltering {
return filteredTasks?.count ?? 0
}
return manager.tasks.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Keys.cell.rawValue, for: indexPath) as! ToDoCell
var currentItem: Task
if isFiltering {
currentItem = filteredTasks?[indexPath.row] ?? manager.tasks[indexPath.row]
} else {
currentItem = manager.tasks[indexPath.row]
}
cell.titleLabel.text = currentItem.taskName
cell.descriptionLabel.text = currentItem.description
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let accessoryType: UITableViewCell.AccessoryType = manager.changeState(at: indexPath.row) ? .checkmark : .none
tableView.cellForRow(at: indexPath)?.accessoryType = accessoryType
}
When you use tableView.dequeueReusableCell, you may get the old cell, so you should update it. You should read doc.
#PGDev already said in comments that you should save checked/unchecked status in your model.
I hope my example will help you.
You can contain state of cells in cell models:
class YourCellModel {
var task: Task
var checked: Bool
init(task: Task, checked: Bool) {
self.task = task
self.checked = checked
}
}
And add it in ToDoCell:
//...
var model: YourCellModel {
didSet {
updateViews()
}
}
func updateViews() {
titleLabel.text = task.taskName
descriptionLabel.text = task.description
if model.checked {
//...
} else {
//....
}
}
And update model here:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Keys.cell.rawValue, for: indexPath) as! ToDoCell
// You should contain cell models to remember their states
let model = cellModels[indexPath.row]
cell.model = model
return cell
}
When the user checks a cell, you should save it in your cell model. You can do it in ToDoCell:
func checked() {
model.checked = true
}
Note: If isFiltering is true, it is a different array of cell models.
UPD. I noticed your Task is similar to a cell model. You can save checked status there. But your cell should have access to it.

Get textLabel from UITableView

I need to get textLabel from row in UITableView. But I get nil. I need to get textLabel, because I'm using UISearchBar, if I will try to get data using index, when searching, I will receive incorrect indexes. So , I want to get textLabel.
Please, fix where I'm wrong
When I am typing in searchBar items in TableView change. But index doesn't. For example Food = ["Apple", "Banana", "Coca-Cola"]. If I use searchBar and enter "Banana". Then I click on this , but I get Apple (because this is index - 0). That's why I want to get textLabel
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//let meal = foods[indexPath.item]
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let labelContent = cell.textLabel!.text
print(labelContent)
}
UISearchBar
extension FoodViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchedFoods = foods.filter({ $0.title.lowercased().prefix(searchText.count) == searchText.lowercased() })
searching = true
tableView.reloadData()
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searching = false
searchBar.text = ""
tableView.reloadData()
}
}
Never get data from the view, the cell, get it always from the model, the data source.
And never use dequeueReusableCell outside of cellForRowAt. You won't get the cell you expect.
In this case you have to get the data depending on searching
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let labelContent : String
if searching {
labelContent = searchedFoods[indexPath.row].title
} else {
labelContent = foods[indexPath.row].title
}
print(labelContent)
}
And your filter method is horrible. Change it to much more efficient
searchedFoods = foods.filter { $0.title.range(of: searchText, options: [.caseInsensitive, .anchored] != nil) }
Finally I recommend to change textDidChange to cancel searching also if the search text becomes empty and remove the unused items from searchedFoods.
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.isEmpty {
searchedFoods.removeAll()
searching = false
} else {
searchedFoods = foods.filter{ $0.title.range(of: searchText, options: [.caseInsensitive, .anchored]) != nil }
searching = true
}
tableView.reloadData()
}
As I have figured out the problem is that you are using indexPath.item that's why you are getting the wrong index please try this
let meal = foods[indexPath.row]
If you want to get a text from the UILabel on tap of cell
confirm UITableViewDelegate
//Access the array that you have used to fill the tableViewCell
print(foods[indexPath.row]) it will print selected row
OR
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! UITableViewCell
let labelContent = cell.textLabel!.text
print(labelContent)
}
Lets just say instead of getting data from foods (in didSelect method) get it from searched Food. But for that to work properly you should assign searched food with food initially and also when the user clears search bar you should again reset searched food to food data.
Please try like this,
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if searching {
print(searchedFoods[indexPath.row])
} else {
print(foods[indexPath.row])
}
}
Try This
extension FoodViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
if searching {
let food = searchedFoods[indexPath.row]
cell.textLabel?.text = food.title
} else {
let food = foods[indexPath.row]
cell.textLabel?.text = food.title
}
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searching {
return searchedFoods.count
} else {
return foods.count
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if searching {
let meal = searchedFoods[indexPath.row]
let labelContent = meal
print(labelContent)
} else {
let meal = foods[indexPath.row]
let labelContent = meal
print(labelContent)
}
}

Remove index from sidemenu user type wise

I have implemented side menu in tableview and now my scenario is like, I have to manage sidemenu options as user types
Let me show my code
var items = ["Social Media Post", "Messages", "Manage User","My Account","Information","Logout"]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! MenuTableViewCell
cell.lblTitle.text = items[indexPath.row]
cell.imgMenuLogo.image = image[indexPath.row]
print(User_type)
if User_type == 2{
items.remove(at: 0)
}
return cell
}
but now i want . to de like this
if user_type == "3"{
// Social Media , Messages And Manage User options i want to remove
}
I am not able to understand how to remove from index.
Try something like this:
override func viewDidLoad() {
super.viewDidLoad()
getList()
}
func getList(){
switch userType{
case 0:
items = ["UserTypeOne_Home","UserType_One Settings","etc"]
break
case 1:
items = ["UserTypeTwo_Home","UserType_Two Settings","etc"]
break
default:
break
}
self.tableView.reloadData()
}
extension ViewController: UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "Some ID")
cell?.textLabel?.text = items[indexPath.row]
return cell!
}
}
Try not to change the array from within the cellForRowAt indexPath method using indexPath.row, that will not give you the result you want. Modulate the array from outside the protocol method overrides, and just call the reloadData() method.
Try to use enum of UserType and check type of current user than Make an array with default options available to every user and then append specific data in array according to user type. Hope it clarifies :)
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! MenuTableViewCell
cell.lblTitle.text = items[indexPath.row]
cell.imgMenuLogo.image = image[indexPath.row]
print(User_type)
if User_type == 2{
items.remove(at: 0)
}
return cell
}
This will work, But you have done a small mistake here.
You have removed from array after setting label. So you need to remove the item from array first then do set label.
Btw, I will not recommend this method as you need to add/remove from array for every cellForRowAt method.

Assigning an array count to a tableviewcell label

I have a posts array in which I'm returning all the posts from a PHP file. I'm trying to assign the number of posts to a label in a tableview cell. However, when I assign the number of posts to a label, I'm getting a nil value. Can anyone help with this?
var posts = [AnyObject]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1
} else {
return posts.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! InfoCell
print(posts.count)
cell.PostsLbl.text = String(posts.count)
return cell
}
}
It looks like you are getting posts async from PHP file and after you get them you reload only the second section.