I have a search function in my app which gets data from a fetchedResultsController. The problem is when I display the filtered data in the tableView everytime it gets to a new section, the array starts over and over (due to indexPath.row being 0 everytime indexPath.section increments). I've never been good at nested arrays and I thought this is the perfect time to learn them, since I can't get over my problem without this array.
So I have this array which is the filtered data out of the fetchedResultsController:
filteredItems = (fetchedResultsController.fetchedObjects?.filter({(budget : Budget) -> Bool in
return (budget.dataDescription?.lowercased().contains(searchText.lowercased()))!
}))!
How can I make an array called filteredObjects which sorts my items for sections? For example
- Section 1 ( filteredObjects[0] ):
item 1 ( filteredObjects[0][1] )
item 2 ( filteredObjects[0][2] )
-
Section 2 ( filteredObjects[1] ):
item 1 ( filteredObjects[1][0] )
etc
Use below method to define number of sections
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return filteredObjects.count
}
And, for number of rows
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredObjects[section].count
}
And Finally, for CellForRowAtIndexpath
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TaskTableViewCell
let currentItem = filteredObjects[indexPath.section][indexPath.row]
... Here, use currentItem as whatever it is (Object or dictionary)
return cell
}
let budgets = [Budget]()
let searchResult = [Budget]()
You should always use searchResult array in tableview datasource methods. initially you should add all objects of budgets array to searchResult & load table view.
when search started remove all items from searchResult and add filtered result to search result array & reload tableview.
func search(searchText:String){
searchResult.removeAll()
let result = budgets.filter({
var budget = $0
let filtered = budget.expenses.filter({
if let deptName = $0.deptName{
return deptName.lowercased().contains(searchText.lowercased())
}
return false
})
budget.expenses = filtered
return budget.expenses.count != 0
})
searchResult.append(contentsOf: result)
}
struct Budget {
var expenses = [Expense]()
}
struct Expense{
var deptName:String?
}
Related
I am fetching previously selected categorylist from the server. say for an example.cateogrylist i fetched from the server was in following formate
categoryid : 2,6,12,17
now what i need to do is want to enable checkmark in my tableview based on this categorylist,for that purpose i converted this list into an [Int] array like this :
func get_numbers(stringtext:String) -> [Int] {
let StringRecordedArr = stringtext.components(separatedBy: ",")
return StringRecordedArr.map { Int($0)!}
}
in viewDidLoad() :
selectedCells = self.get_numbers(stringtext: UpdateMedicalReportDetailsViewController.catId)
print(myselection)
while printing it's giving me results like this : [12,17,6,8,10]
i want to enable checkimage based on this array.I tried some code while printing its giving me the right result like whatever the categories i selected at the time of posting ,i am able to fetch it but failed to place back this selection in tableview.Requirement : while i open this page it should show me the selection based on the categorylist i fetched from the server.
var selectedCells : [Int] = []
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell1 = table.dequeueReusableCell(withIdentifier: "mycell") as! catcell
cell1.mytext.text = categoriesName[indexPath.row]
if UpdateMedicalReportDetailsViewController.flag == 1
{
selectedCells = self.get_numbers(stringtext: UpdateMedicalReportDetailsViewController.catId)
cell1.checkimage.image = another
print(selectedCells)
}
else
{
selectedCells = []
cell1.checkimage.image = myimage
}
return cell1
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = table.cellForRow(at: indexPath) as! catcell
cell.checkimage.image = myimage
if cell.isSelected == true
{
self.selectedCells.append(indexPath.row)
cell.checkimage.image = another
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let cell = table.cellForRow(at: indexPath) as! catcell
if cell.isSelected == false
{
self.selectedCells.remove(at: self.selectedCells.index(of: indexPath.row)!)
cell.checkimage.image = myimage
}
}
output :
This is a very common use case in most apps. I'm assuming you have an array of all categories, and then an array of selected categories. What you need to do is in cellForRowAtIndexPath, check to see if the current index path row's corresponding category in the "all categories" array is also present in the "selected categories" array. You can do this by comparing id's etc.
If you have a match, then you know that the cell needs to be selected/checked. A clean way to do this is give your cell subclass a custom load method and you can pass a flag for selected/checked.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = table.dequeueReusableCell(withIdentifier: "mycell") as! catcell
let category = self.categories[indexPath.row] // Let's say category is a string "hello"
Bool selected = self.selectedCategories.contains(category)
cell.load(category, selected)
return cell
}
So with the code above, let's say that categories is just an array of category strings like hello, world, and stackoverflow. We check to see if the selectedCategories array contains the current cell/row's category word.
Let's say that the cell we're setting up has a category of hello, and selectedCategories does contain it. That means the selected bool gets set to true.
We then pass the category and selected values into the cell subclass' load method, and inside that load method you can set the cell's title text to the category and you can check if selected is true or false and if it's true you can display the checked box UI.
I am making an app in which I need this thing in one of the screens.
I have used the tableview with sections as shown in the code below
var sections = ["Adventure type"]
var categoriesList = [String]()
var items: [[String]] = []
override func viewDidLoad() {
super.viewDidLoad()
categoryTableView.delegate = self
categoryTableView.dataSource = self
Client.DataService?.getCategories(success: getCategorySuccess(list: ), error: getCategoryError(error: ))
}
func getCategorySuccess(list: [String])
{
categoriesList = list
let count = list.count
var prevInitial: Character? = nil
for categoryName in list {
let initial = categoryName.first
if initial != prevInitial { // We're starting a new letter
items.append([])
prevInitial = initial
}
items[items.endIndex - 1].append(categoryName)
}
for i in 0 ..< count
{
var tempItem = items[i]
let tempSubItem = tempItem[0]
let char = "\(tempSubItem.first)"
sections.append(char)
}
}
func getCategoryError(error: CError)
{
print(error.message)
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.sections[section]
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = categoryTableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath)
cell.textLabel?.text = self.items[indexPath.section][indexPath.row]
return cell
}
But it is producing runtime errors on return self.items[section].count
The reason for this error is because I am loading data (items array) is from server and then populating sections array after it. At the time when tableview gets generated, both the sections and items array is empty. That is why error occurs.
I am new to iOS and not getting grip over how to adjust data in sections of tableview.
Can someone suggest me a better way to do this?
What should be number of rows in section when I have no idea how much items server call will return?
Also i want to cover the case when server call fails and no data is returned. Would hiding the tableview (and showing error message) be enough?
Any help would be much appreciated.
See if this works: Make your data source an optional:
var items: [[String]]?
And instantiate it inside your getCategorySuccess and fill it with values. Afterwards call categoryTableView.reloadData() to reload your table view.
You can add a null check for your rows like this:
return self.items?[section].count ?? 0
This returns 0 as a default. Same goes for number of sections:
return self.items?.count ?? 0
In case the call fails I would show an error message using UIAlertController.
Your comment is incorrect: "At the time when tableview gets generated, both the sections and items array is empty. That is why error occurs."
According to your code, sections is initialized with one entry:
var sections = ["Adventure type"]
This is why your app crashes. You tell the tableview you have one section, but when it tries to find the items for that section, it crashes because items is empty.
Try initializing sections to an empty array:
var sections = [String]()
Already things should be better. Your app should not crash, although your table will be empty.
Now, at the end of getCategorySuccess, you need to reload your table to reflect the data retrieved by your service. Presumably, this is an async callback, so you will need to dispatch to the main queue to do so. This should work:
DispatchQueue.main.async {
self.categoryTableView.reloadData()
}
I have list of product items to display in my table view. At the same time i have i have some other api call, Where i will pass my prodcut item name to check. If that product item is available then that particular data or item cell alone will be highlighted and it will be disabled.
Now what i need is, when i do api call, and after that if that particular data or product name is available in that api, instead of highlight and disable... I should not show that particular data in my table view.
How to do that:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! AllConnectionsTableViewCell
if let contact = filtered?[indexPath.row]{
cell.emailOutlet.text = AccountDataCache.sharedInstance.displayMaskAccnt(items: product.name)
cell.nameOutlet.text = product.name
if let _ = self.checkapicall(items: product.name){
// here if my product name is availble in api, then only the backgroudnd and it will be disabled
if let product = filtered?[indexPath.row]{
cell.namelabel.text = product.name
if let _ = self.checkapicall(items: product.vpa){
cell.cellOuterView.backgroundColor = UIColor.red
cell.isUserInteractionEnabled = false
}else{
cell.cellOuterView.backgroundColor = UIColor.white
cell.isUserInteractionEnabled = true
}
}
}
Instead of chnaging BG, Disable..i should not show that data in that tableview cell.How to do that.?
Thanks
As you described, if your data looks like this:
name1, name2,name3, name4
Then you want to show four rows in your tableView.
If name2 is available in your API call then you want to show this:
name1, name3, name4
So what you need to do is to get all the names before you start updating the tableView. This is because you need to set how many rows you want to display in your tableView.
You could do something like this (I´m not sure how you fetch your data today, but this is an example to get you started):
// check add edit to your product
var products = [Product(name: "name1", vpa: "1"), Product(name: "name2", vpa: "2"), Product(name: "name3", vpa: "3"), Product(name: "name4", vpa: "4")]
// set the produts count
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return products.count
}
// just set the name here, don´t make any checks
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "StartPageCell", for: indexPath)
cell.namelabel.text = product.name
return cell
}
// check the names here and then reload the tableView
func checkNames() {
for product in products {
if self.checkapicall(items: product.vpa){ {
if let index = products.index(where: { $0.vpa == vpa }) {
products.remove(at: index)
}
}
}
tableView.reloadData()
}
First of all don't make such checks in cellForRow, make it in viewDidLoad or viewWillAppear
Add a property var isAvailable = false to your product model
In viewDidLoad or viewWillAppear check the availability of the products and set isAvailable accordingly.
Create the data source array var filtered = [Product]() (assuming Product is the data model) and filter the items filtered = allItems.filter { $0.isAvailable }
Reload the table
I have a one view app with embedded UITableView that displays a list of "stores"(Realm object). By default I populate the table view of all the Store objects. IF the user wants to then narrow the results they can do so by using any combination of text fields in MasterVC. When they hit search - simply update TableView with 'filtered' Realm objects.
What works:
Populate UITableView with objects from the Realm.
Create new Realm entries via text field entries in MasterVC and repopulate table in ResultsVC.
Swipe to delete object on table / and Realm object.
What sort of works:
If user enters a search term then 'filter' the Realm object (Stores) and repopulate the table. This correctly reloads and returns the number of results. However the First Cell (0) of the TableView is always the exact same and never updates.. If there are 20 returned results in the search then Rows 1-18 are correctly displayed. Row 0 is static and never changes its text. Any obvious reasons why?
Results Table View Controller
class ResultsVC: UITableViewController {
// data source
var stores: Results<Store> = {
let realm = try! Realm()
return realm.objects(Store.self)
}()
var token: NotificationToken?
...
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return stores.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) as! ResultsCustomViewCell
let stores = realm.objects(Store.self)
let currentStore = stores[indexPath.row]
cell.storeNumber.text = "#\(currentStore.storeNumber)"
cell.storeName.text = "\"\(currentStore.storeName)\""
return cell
}
}
Here is how I'm accessing the ResultsVC from MasterVC
Master View Controller
class MasterViewController: UIViewController {
...
#IBAction func searchDatabase(_ sender: Any) {
let CVC = childViewControllers.first as! UINavigationController
let resultVC = CVC.viewControllers[0] as? ResultsVC
result.stores = stores.filter("address = '1234 Blue Street'")
result.tableView.reloadData()
}
...
}
Turns out I had a duplicate variable which was overwriting the orig from above.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) as! ResultsCustomViewCell
let stores = realm.objects(Store.self) // <- OVERWRITING ORIGINAL //
let currentStore = stores[indexPath.row]
cell.storeNumber.text = "#\(currentStore.storeNumber)"
cell.storeName.text = "\"\(currentStore.storeName)\""
return cell
}
I am having an issue displaying indexed objects in a table view. I have indexed the objects as a list of clients based on the first letter of their name. The indexed results are put into a dictionary like this
{Char: [Client]}
Char being the first character of the client's name and [Client] being an array of client objects, who have the first letter of their name matching the Char. When printed out, this shows up like this:
{'D': [Client("David"), Client("Dan")]}
However, when I go to set these titles in the tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) function, I get an index out of bounds error. The client array has a count of 3 and the contacts dictionary has a count of two, but has all 3 objects it as such:
{'S': [Client("Sam")], 'D': [Client("David"), Client("Dan")]}
How do I go through the dictionary properly to get individual clients into each table cell with the proper section headers? I am using Swift 3.0. Below I have posted how I indexed it as well as the function I am trying to override.
ClientTableViewController.swift
var clients = Client.loadAllClients()
var contacts = [Character: [Client]]()
var letters: [Character] = []
override func viewDidLoad() {
super.viewDidLoad()
letters = clients.map { (name) -> Character in
return name.lName[name.lName.startIndex]
}
letters = letters.reduce([], { (list, name) -> [Character] in
if !list.contains(name) {
return list + [name]
}
return list
})
for c in clients {
if contacts[c.lName[c.lName.startIndex]] == nil {
contacts[c.lName[c.lName.startIndex]] = [Client]()
}
contacts[c.lName[c.lName.startIndex]]!.append(c)
}
for (letter, list) in contacts {
contacts[letter] = list.sorted(by: { (client1, client2) -> Bool in
client1.lName < client2.lName
})
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Name", for: indexPath) as! ClientTableViewCell
cell.clientName?.text = contacts[letters[indexPath.row]]?[indexPath.row].lName
return cell
}
Create one section per letter, by implementing numberOfSections method to return this:
return letters.count
Change code in cellForRowAt from this:
cell.clientName?.text = contacts[letters[indexPath.row]]?[indexPath.row].lName
To this:
cell.clientName?.text = contacts[letters[indexPath.section]]?[indexPath.row].lName