Click here to Skip to main content
15,885,309 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have been looking for an example of how to create a grouped TableView in Swift but have had no luck.. I am working on a project to create a Categories Page and currently have a working search bar as well as the sub-categories listed in a TableView.. I'd like to be able to break these categories into a grouped TableView so that it is easier for the user.. Can anyone help me find a good example which can guide me? Or provide any advice? I was thinking since in my array I already have a category defined for each.. that I would try and break it up by Travel, Wireless Phones, and Entertainment?

I'm pretty new to this so anything helps!


Here is what I have in my Category.swift file:

Java
import Foundation

struct Category {
    let category : String
    let name : String
}

And here is what I have so far for my CategoryTableViewController:

import UIKit

class CategoryTableViewController : UITableViewController, UISearchBarDelegate, UISearchDisplayDelegate {
    
    var categories = [Category]()
    
    var filteredCategories = [Category]()
    
    override func viewDidLoad() {
        
        // Sample Data for categoryArray
        self.categories = [Category(category:"Travel", name:"Rental Cars"),
            Category(category:"Travel", name:"Hotels"),
            Category(category:"Travel", name:"Cruises and Tours"),
            
            Category(category:"Entertainment", name:"Amusement Parks"),
            Category(category:"Entertainment", name:"Movie Tickets"),
            Category(category:"Entertainment", name:"Sports Tickets"),
            
            Category(category:"Cell Phones", name:"Accessories"),
            Category(category:"Cell Phones", name:"Wireless Carriers"),]
    
        
        // Reload the table
        self.tableView.reloadData()
    }
    /*
    override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
    }
    
    // MARK: - Table view data source
    
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1
    }


*/
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == self.searchDisplayController!.searchResultsTableView {
            return self.filteredCategories.count
        } else {
            return self.categories.count
        }
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        //ask for a reusable cell from the tableview, the tableview will create a new one if it doesn't have any
        let cell = self.tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell
        
        var category : Category
        // Check to see whether the normal table or search results table is being displayed and set the Category object from the appropriate array
        if tableView == self.searchDisplayController!.searchResultsTableView {
            category = filteredCategories[indexPath.row]
        } else {
            category = categories[indexPath.row]
        }
        
        // Configure the cell
        cell.textLabel!.text = category.name
        cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
        
        return cell
    }
    
    func filterContentForSearchText(searchText: String, scope: String = "All") {
        self.filteredCategories = self.categories.filter({( category : Category) -> Bool in
            var categoryMatch = (scope == "All") || (category.category == scope)
            var stringMatch = category.name.rangeOfString(searchText)
            return categoryMatch && (stringMatch != nil)
        })
    }
    
    func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchString searchString: String!) -> Bool {
        let scopes = self.searchDisplayController!.searchBar.scopeButtonTitles as [String]
        let selectedScope = scopes[self.searchDisplayController!.searchBar.selectedScopeButtonIndex] as String
        self.filterContentForSearchText(searchString, scope: selectedScope)
        return true
    }
    
    func searchDisplayController(controller: UISearchDisplayController!,
        shouldReloadTableForSearchScope searchOption: Int) -> Bool {
            let scope = self.searchDisplayController!.searchBar.scopeButtonTitles as [String]
            self.filterContentForSearchText(self.searchDisplayController!.searchBar.text, scope: scope[searchOption])
            return true
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        self.performSegueWithIdentifier("categoryDetail", sender: tableView)
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
        if segue.identifier == "categoryDetail" {
            let categoryDetailViewController = segue.destinationViewController as UIViewController
            if sender as UITableView == self.searchDisplayController!.searchResultsTableView {
                let indexPath = self.searchDisplayController!.searchResultsTableView.indexPathForSelectedRow()!
                let destinationTitle = self.filteredCategories[indexPath.row].name
                categoryDetailViewController.title = destinationTitle
            } else {
                let indexPath = self.tableView.indexPathForSelectedRow()!
                let destinationTitle = self.categories[indexPath.row].name
                categoryDetailViewController.title = destinationTitle
            }
        }
    }
}
Posted
Updated 26-Oct-14 11:22am
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900