UISearchBar not updating - ios

I have a UIViewControllerand I added UITableViewController in it and I am adding search bar programmatically. I am able to print the result after searching on the console but when I click on the search bar the custom table cells are still populated and search doesn't update them at all.
I have print statement in the override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell to check if the search controller is active and it never prints that statement.
import UIKit
import Parse
class MasterViewController: UITableViewController, UISearchResultsUpdating, UISearchBarDelegate {
#IBOutlet var mTableView: UITableView!
var detailViewController: DetailViewController? = nil
var objects = [AnyObject]()
var resultSearchController = UISearchController()
var filteredData : NSMutableArray = []
var sectionInTable : NSMutableArray = ["Grand Haven 9", "Holland 7"]
var movieTitle : NSMutableArray = ["The Hunger Game 2","Creed"]
var movieTimeSection1 : NSMutableArray = ["11:00am, 11:40, 12:10pm, 1:25, 2:30, 6:05, 6:55, 7:30, 9:05", "11:10am, 11:50, 12:20pm, 2:25, 3:30, 6:05, 6:55, 8:30, 10:05"]
var movieTimeSection2 = ["Title": "Martian", "Theatre": "Holland 7", "Time": "11:00am, 11:40, 12:10pm, 1:25, 2:30, 6:05, 6:55, 7:30, 9:05"]
var onlineMovieTitle : NSMutableArray = []
var movieSection1 : NSMutableArray = []
var movieSection2 : NSMutableArray = []
override func viewDidLoad() {
super.viewDidLoad()
print(movieSection1)
print(movieSection2)
self.tableView.separatorColor = UIColor.cloudsColor()
self.tableView.backgroundColor = UIColor.cloudsColor()
self.resultSearchController = ({
let controller = UISearchController(searchResultsController: nil)
controller.searchResultsUpdater = self
controller.dimsBackgroundDuringPresentation = false
controller.searchBar.delegate = self
controller.searchBar.sizeToFit()
controller.preferredStatusBarStyle() == UIStatusBarStyle.LightContent
controller.hidesNavigationBarDuringPresentation = false
self.mTableView.tableHeaderView = controller.searchBar
return controller
})()
//self.resultSearchController.searchBar.endEditing(true)
}
func updateSearchResultsForSearchController(searchController: UISearchController){
filteredData.removeAllObjects()
let searchPredicate = NSPredicate(format: "Title CONTAINS %#", searchController.searchBar.text!.uppercaseString)
let array = (movieSection1 as NSArray).filteredArrayUsingPredicate(searchPredicate)
let array2 = (movieSection2 as NSArray).filteredArrayUsingPredicate(searchPredicate)
//let array2 = (movieTimeSection1 as NSArray).filteredArrayUsingPredicate(searchPredicate)
filteredData.addObjectsFromArray(array)
filteredData.addObjectsFromArray(array2)
print(filteredData)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.resultSearchController.searchBar.hidden = false
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var count : Int = 0
if (self.resultSearchController.active) {
return 2
}
else {
if section == 0 {
count = movieSection1.count
} else if section == 1 {
count = movieSection2.count
}
}
return count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : MainTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! MainTableViewCell
//Fancy Cells
var corners : UIRectCorner = UIRectCorner.AllCorners
if (tableView.numberOfRowsInSection(indexPath.section) == 1) {
corners = UIRectCorner.AllCorners
} else if (indexPath.row == 0) {
corners = UIRectCorner.TopLeft.union(UIRectCorner.TopRight)
} else if (indexPath.row == tableView.numberOfRowsInSection(indexPath.section) - 1) {
corners = UIRectCorner.BottomLeft.union(UIRectCorner.BottomRight)
}
cell.configureFlatCellWithColor(UIColor.greenSeaColor(), selectedColor: UIColor.cloudsColor(), roundingCorners: corners)
//Fancy Buttons
cell.cornerRadius = 7
if indexPath.row == 0 {
cell.trailorButton.addTarget(self, action: "openHunger:", forControlEvents: UIControlEvents.TouchUpInside)
}else if indexPath.row == 1{
cell.trailorButton.addTarget(self, action: "openCreed:", forControlEvents: UIControlEvents.TouchUpInside)
}
cell.trailorButton.layer.cornerRadius = 5
cell.trailorButton.tintColor = UIColor.whiteColor()
let movieNameStr = movieTitle[indexPath.row] as! String
cell.movieImage.image = UIImage(named: movieNameStr)
//Cell Data Insertion
if (self.resultSearchController.active){
print("search ---------------")
cell.movieName.text = filteredData[indexPath.row].valueForKey("Title") as? String
cell.movieDetail.text = filteredData[indexPath.row].valueForKey("Time") as? String
return cell
}else {
print("cell")
if indexPath.section == 0 {
cell.movieName.text = movieSection1[indexPath.row].valueForKey("Title") as? String
cell.movieDetail.text = movieSection1[indexPath.row].valueForKey("Time") as? String
} else if indexPath.section == 1 {
cell.movieName.text = movieSection2[indexPath.row].valueForKey("Title") as? String
cell.movieDetail.text = movieSection2[indexPath.row].valueForKey("Time") as? String
}
return cell
}
//return cell
}
#IBAction func openHunger(sender: AnyObject) {
UIApplication.sharedApplication().openURL(NSURL(string: "https://youtu.be/n-7K_OjsDCQ")!)
}
#IBAction func openCreed(sender: AnyObject) {
UIApplication.sharedApplication().openURL(NSURL(string: "https://youtu.be/fCBzWLVQgk8")!)
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.sectionInTable[section] as? String
}
}
Any help will be highly appreciated. Thanks

I missed it and thanks to Larcerax the problem was solved by adding mTableView.reloadData()

Related

Search results are cut off when searching TableView

My search is working correctly except the display is not working as expected. When I am performing a search, the last search result is slightly cut off and the portion of the display is all gray. I would expect it to remain the same background color as the rows.. Any help would be appreciated.
EDIT:
import UIKit
import Foundation
// For search
extension MasterViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
filterContentForSearchText(searchText: searchController.searchBar.text!)
}
}
class MasterViewController: UITableViewController {
let searchController = UISearchController(searchResultsController: nil)
var filteredFighters = [Fighter]()
var detailViewController: DetailViewController? = nil
var objects = [Any]()
// Creates array of fighters
var fighterArray = [Fighter]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
// Access all the data from JSON
let JR = JSONReceiver()
fighterArray = JR.populateFighterJSONArray()
// Search related
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
definesPresentationContext = true
tableView.tableHeaderView = searchController.searchBar
navigationItem.title = "UFC Champions"
self.navigationController?.navigationBar.barTintColor = UIColor.black
self.navigationController?.navigationBar.tintColor = UIColor.white
self.navigationController?.navigationBar.titleTextAttributes = [ NSForegroundColorAttributeName : UIColor.white, NSFontAttributeName: UIFont(name: "Arial", size: 26)!]
}
// FOr search
func filterContentForSearchText(searchText: String, scope: String = "All") {
filteredFighters = fighterArray.filter { fighter in
return fighter.name.lowercased().contains(searchText.lowercased())
}
tableView.reloadData()
}
override func viewWillAppear(_ animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.isCollapsed
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/* DONT BELIEVE THIS IS NEEDED - DO NOT SEE IN PROFESSORS CODE
func insertNewObject(_ sender: Any) {
objects.insert(NSDate(), at: 0)
let indexPath = IndexPath(row: 0, section: 0)
self.tableView.insertRows(at: [indexPath], with: .automatic)
} */
// MARK: - Segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Determines which row was selected (e.g. which fighters, say element 1 points to fighter1)
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
// let stud = StudentsArray[indexPath.row]
let fighter: Fighter
if searchController.isActive && searchController.searchBar.text != "" {
fighter = filteredFighters[indexPath.row]
} else {
fighter = fighterArray[indexPath.row]
}
let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
// Makes sure selected student points to the correct controller
controller.detailItem = fighter
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchController.isActive && searchController.searchBar.text != "" {
return filteredFighters.count
}
return fighterArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let fighter: Fighter
if searchController.isActive && searchController.searchBar.text != "" {
fighter = filteredFighters[indexPath.row]
} else {
fighter = fighterArray[indexPath.row]
}
cell.textLabel!.text = fighter.name
cell.detailTextLabel?.text = fighter.record
cell.imageView?.image = UIImage(named: fighter.fighterImage)
self.tableView .sizeToFit()
// cell.detailTextLabel?.text = "fighterTest"
return cell
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return false
}
}

Mapping between TableView and SearchView

I have a searchController added programatically to my UIViewController on top of my table view. My ViewController handles segues based on rowIndex which poses a problem with my searchview which alters the indices. I have added a mapping array to fix that, but its not working as intended, with out of bounds errors sometimes and it not matching to correct elements. My code below.
import UIKit
class WebpageController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UISearchResultsUpdating {
var names: [String] = [String]()
var counter = 0
var counter2 = 0
var school: String = String()
var index: Int = Int()
var searchResults: [String] = [String]()
var searchController = UISearchController(searchResultsController: nil)
var searchIndex: [Int] = [Int]()
#IBOutlet var tables: UITableView!
var refreshControl: UIRefreshControl!
override func viewDidLoad() {
super.viewDidLoad()
searchController.searchResultsUpdater = self
searchController.hidesNavigationBarDuringPresentation = false
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.sizeToFit()
definesPresentationContext = true
tables.tableHeaderView = searchController.searchBar
names = HtmlController.loadData() as NSArray as! [String]
names.removeAtIndex(0)
clean()
refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(WebpageController.refresh(_:)), forControlEvents: UIControlEvents.ValueChanged)
tables.addSubview(refreshControl)
// Do any additional setup after loading the view.
}
func refresh(sender: AnyObject)
{
names = HtmlController.loadData() as NSArray as! [String]
names.removeAtIndex(0)
clean()
tables.reloadData()
refreshControl.endRefreshing()
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
let searchText = searchController.searchBar.text
filterContentForSearchText(searchText!)
tables.reloadData()
}
func filterContentForSearchText(searchText: String)
{
if(searchText == "")
{
searchResults = names
}
else{
searchResults = names.filter({ ( a: String) -> Bool in
let nameMatch = a.rangeOfString(searchText, options:
NSStringCompareOptions.CaseInsensitiveSearch)
return nameMatch != nil
})
while counter2 < searchResults.count
{
while counter < names.count{
if names[counter] == searchResults[counter2]
{
if searchIndex.count > counter2 && counter > 0
{
searchIndex.removeAtIndex(counter2)
}
searchIndex.insert(counter, atIndex: counter2)
}
counter += 1
}
counter2 += 1
}
}
}
#IBOutlet weak var Table: UITableView!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func clean()
{
var length = names.count
var i = 0;
var bool = false
let defaults = NSUserDefaults.standardUserDefaults()
if defaults.objectForKey("School") == nil
{
school = "11Staff"
defaults.setObject("11", forKey: "School")
}
else{
school = (defaults.objectForKey("School") as! String) + "Staff"
}
var extra: [String] = [String]()
let bundleidentifier = NSBundle.mainBundle().bundleIdentifier
if let aStreamReader = StreamReader(path: NSBundle.mainBundle().pathForResource(school, ofType: "txt")!)
{
defer {
aStreamReader.close()
}
while let line = aStreamReader.nextLine() {
extra.append(line)
}
}
for String in extra
{
while i < length && bool == false
{
if((String.rangeOfString(names[i].uppercaseString)) != nil)
{
names.removeAtIndex(i)
i -= 1
bool = true
length = names.count
}
i+=1;
}
bool = false
i = 0;
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if searchController.active
{
return searchResults.count
}
else{
return names.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell
if let reusedCell = tableView.dequeueReusableCellWithIdentifier("Cell") {
cell = reusedCell
} else {
cell = UITableViewCell(style: .Default, reuseIdentifier: "Cell")
}
if !searchController.active{
if let label = cell.textLabel {
label.text = names[indexPath.row].uppercaseString
}
}
else{
cell.textLabel!.text = searchResults[indexPath.row].uppercaseString
}
return cell }
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
index = indexPath.row
performSegueWithIdentifier("WebTransfer", sender:self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let Destination: WebsiteController = segue.destinationViewController as! WebsiteController
if !searchController.active
{
Destination.index = index
}
else{
Destination.index = searchIndex[index]
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}

Adding Searchbar to table view returns unwrapping nil view

Im attempting to add a search bar to a table view that displays names. Im getting a unwrapping nil error when i try to add it as a subheader to my tableview. Im not sure why. The point where the error occurs is marked.
import UIKit
class WebpageController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UISearchResultsUpdating {
var names: [String] = [String]()
var school: String = String()
var index: Int = Int()
var searchResults: [String] = [String]()
var searchController = UISearchController(searchResultsController: nil)
#IBOutlet weak var tables: UITableView!
var refreshControl: UIRefreshControl!
override func viewDidLoad() {
super.viewDidLoad()
searchController.searchResultsUpdater = self
searchController.hidesNavigationBarDuringPresentation = false
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.sizeToFit()
definesPresentationContext = true
tables.tableHeaderView = searchController.searchBar //returns error
names = HtmlController.loadData() as NSArray as! [String]
clean()
refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(WebpageController.refresh(_:)), forControlEvents: UIControlEvents.ValueChanged)
tables.addSubview(refreshControl)
// Do any additional setup after loading the view.
}
func refresh(sender: AnyObject)
{
names = HtmlController.loadData() as NSArray as! [String]
clean()
tables.reloadData()
refreshControl.endRefreshing()
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
let searchText = searchController.searchBar.text
filterContentForSearchText(searchText!)
tables.reloadData()
}
func filterContentForSearchText(searchText: String)
{
if(searchText == "")
{
searchResults = names
}
else{
searchResults = names.filter({ ( a: String) -> Bool in
let nameMatch = a.rangeOfString(searchText, options:
NSStringCompareOptions.CaseInsensitiveSearch)
return nameMatch != nil
})
}
}
#IBOutlet weak var Table: UITableView!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func clean()
{
var length = names.count
var i = 0;
var bool = false
let defaults = NSUserDefaults.standardUserDefaults()
if defaults.objectForKey("School") == nil
{
school = "11Staff"
defaults.setObject("11", forKey: "School")
}
else{
school = (defaults.objectForKey("School") as! String) + "Staff"
}
var extra: [String] = [String]()
let bundleidentifier = NSBundle.mainBundle().bundleIdentifier
if let aStreamReader = StreamReader(path: NSBundle.mainBundle().pathForResource(school, ofType: "txt")!)
{
defer {
aStreamReader.close()
}
while let line = aStreamReader.nextLine() {
extra.append(line)
}
}
for String in extra
{
while i < length && bool == false
{
if((String.rangeOfString(names[i].uppercaseString)) != nil)
{
names.removeAtIndex(i)
i -= 1
bool = true
length = names.count
}
i+=1;
}
bool = false
i = 0;
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if searchController.active
{
return searchResults.count
}
else{
return names.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell
if let reusedCell = tableView.dequeueReusableCellWithIdentifier("Cell") {
cell = reusedCell
} else {
cell = UITableViewCell(style: .Default, reuseIdentifier: "Cell")
}
if let label = cell.textLabel {
label.text = names[indexPath.row + 1].uppercaseString
}
return cell }
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
index = indexPath.row
performSegueWithIdentifier("WebTransfer", sender:self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let Destination: WebsiteController = segue.destinationViewController as! WebsiteController
Destination.index = index
}
}

found nil while trying to segue away from a tableView

I'm getting errors whenever I try to reference the viewTable in the viewDidLoad AFTER I click on a cell to transition with the segue. Thanks a lot!!
Basically I can't use the segue unless I comment out the tableview references in view did load... but I need those in order to use the search bar and im sure it will cause problems on the way back...
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet var tableView: UITableView! {
didSet {
print("tableView is set")
}
}
let searchController = UISearchController(searchResultsController: nil)
let textCellIdentifier = "TextCell"
var buildings: [(String,String)] = []
var filteredBuildings = [(String,String)]()
var goToIndex: Int?
override func viewDidLoad() {
super.viewDidLoad()
print(tableView)
var buildingTuples = loadBuildings()
for tuple in buildingTuples {
self.buildings.append(tuple)
}
self.goToIndex = -1
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
definesPresentationContext = true
tableView!.tableHeaderView = searchController.searchBar
}
func filterContentForSearchText(searchText: String, scope: String = "All") {
filteredBuildings = buildings.filter { building in
return building.0.lowercaseString.containsString(searchText.lowercaseString)
}
self.tableView.reloadData()
}
// MARK: UITextFieldDelegate Methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//return self.buildings.count
if searchController.active && searchController.searchBar.text != "" {
return filteredBuildings.count
}
return buildings.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
/*
let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath)
let row = indexPath.row
cell.textLabel?.text = buildings[row].0
return cell
*/
let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath)
let tuple: (String, String)
if searchController.active && searchController.searchBar.text != "" {
tuple = filteredBuildings[indexPath.row]
} else {
tuple = buildings[indexPath.row]
}
cell.textLabel?.text = tuple.0
return cell
}
// MARK: UITableViewDelegate Methods
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//tableView.deselectRowAtIndexPath(indexPath, animated: true)
let row = indexPath.row
self.goToIndex = indexPath.row
self.performSegueWithIdentifier("MainToLocation", sender: self)
//print(buildings[row].0)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "MainToLocation" {
let locationViewController = (segue.destinationViewController as! LocationViewController)
locationViewController.building = self.buildings[self.goToIndex!]
}
}
extension ViewController: UISearchResultsUpdating {
func updateSearchResultsForSearchController(searchController: UISearchController) {
filterContentForSearchText(searchController.searchBar.text!)
}
}
You can try this..
let destinationVC = self.storyboard!.instantiateViewControllerWithIdentifier("viewController") as! NextViewController
var alreadyPushed = false
if let vc = self.navigationController?.viewControllers {
for viewController in vc {
if let viewController = viewController as? NextViewController {
self.navigationController?.popToViewController(viewController, animated: true)
print("Push your controller")
alreadyPushed = true
break
}
}
}
if alreadyPushed == false {
self.navigationController?.pushViewController(destinationVC, animated: true)
}

How to filter object array in updateSearchResultsForSearchController when using UISearchController?

My search controller class is as following:
class FeastSearchTableViewController: UITableViewController, UISearchResultsUpdating {
var feastEntries = [FeastEntry]()
var filteredFeasts = [FeastEntry]()
/* let tableData = ["One","Two","Three","Twenty-One"]
var filteredTableData = [String]()*/
var resultSearchController = UISearchController()
override func viewDidLoad() {
super.viewDidLoad()
self.resultSearchController = ({
let controller = UISearchController(searchResultsController: nil)
controller.searchResultsUpdater = self
controller.dimsBackgroundDuringPresentation = false
controller.searchBar.sizeToFit()
self.tableView.tableHeaderView = controller.searchBar
return controller
})()
self.feastEntries = [FeastEntry(category:"Chocolate", name:"chocolate Bar"),
FeastEntry(category:"Chocolate", name:"chocolate Chip"),
FeastEntry(category:"Chocolate", name:"dark chocolate"),
FeastEntry(category:"Hard", name:"lollipop"),
FeastEntry(category:"Hard", name:"candy cane"),
FeastEntry(category:"Hard", name:"jaw breaker"),
FeastEntry(category:"Other", name:"caramel"),
FeastEntry(category:"Other", name:"sour chew"),
FeastEntry(category:"Other", name:"gummi bear")]
// Reload the table
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// 2
if (self.resultSearchController.active) {
return self.filteredFeasts.count
}
else {
return self.feastEntries.count
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let feasts = self.feastEntries[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier("TimelineCellPhoto") as! TimelineCell
cell.typeImageView.image = UIImage(named: "timeline-photo")
cell.profileImageView.image = UIImage(named: "profile-pic-2")
cell.nameLabel.text = feasts.name
cell.photoImageView?.image = UIImage(named: "dish")
cell.dateLabel.text = "2 mins ago"
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("feastDetail", sender: tableView)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if segue.identifier == "feastDetail" {
let candyDetailViewController = segue.destinationViewController as! UIViewController
}
}
func updateSearchResultsForSearchController(searchController: UISearchController)
{
filteredFeasts.removeAll(keepCapacity: false)
let searchPredicate = NSPredicate(format: "category CONTAINS[c] %#", searchController.searchBar.text)
//let array = (feastEntries as NSMutableArray).filteredArrayUsingPredicate(searchPredicate)
/* let array = (feastEntries as NSArray).filteredArrayUsingPredicate(searchPredicate)
filteredFeasts = array as! [String]
*/
self.tableView.reloadData()
}
}
struct FeastEntry {
let category : String
let name : String
}
I have two requirements. First one is as how can I filter feastEntries array on the basis of category inside updateSearchResultsForSearchController.
Second is as how can I implement scope bar filter for this scenario.
Check filter method in swift...using this you can filter any collection type,and you could write something like this:
let filteredEntry = self.feastEntries.filter { $0.0 == “Chocolate”//filter condition }
ScopeBar Implementation:
Create a segmented control with chocolate,hard and other segment ...
Create an IBaction for that segmented control depending on selected segment apply filter on feastEntries array as shown above.

Resources