PopOver TableView, error at cell in Swift IOS 8 - ios

i am using ViewController in my application. in ViewController i try to popOver tableview using textfield. but having error
this my code popUp :
Func textFieldShouldBeginEditing(textField: UITextField) -> Bool{
if (textField == paymentTextField){
var paymentVC = MasterPaymentTableViewController()
paymentVC.modalPresentationStyle = .Popover
paymentVC.preferredContentSize = CGSizeMake(300, 500)
let popOverPresentationVC = paymentVC.popoverPresentationController
popOverPresentationVC?.delegate = self
popOverPresentationVC?.permittedArrowDirections = .Down
popOverPresentationVC?.sourceView = textField as UIView
self.navigationController?.presentViewController(paymentVC, animated: true, completion: nil)
return false
}
}
this error at code :
import UIKit
import CoreData
class MasterPaymentTableViewController: UITableViewController {
var myList : Array<AnyObject> = []
var appDel : AppDelegate!
var context : NSManagedObjectContext!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
appDel = UIApplication.sharedApplication().delegate as! AppDelegate
context = appDel.managedObjectContext
let freq = NSFetchRequest(entityName: "PayMethod")
myList = context.executeFetchRequest(freq, error: nil)!
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 {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myList.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell {
let cellID : String = "Cell"
// ERROR AT HERE : unexpectedly found nil while unwrapping an Optional value
var cell = tableView.dequeueReusableCellWithIdentifier(cellID) as! UITableViewCell
// -------------
if let ip = indexPath {
var myObject : NSManagedObject = myList[ip.row] as! NSManagedObject
let title = myObject.valueForKeyPath("paymentName") as! String
cell.textLabel!.text = title
}
return cell
}
But, if i open tableView directly not from popOver, its working normal
any solution?
thx

Try this:
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
and use the dequeueReusableCellWithIdentifier:forIndexPath: method instead of using dequeueReusableCellWithIdentifier:
let cell = tableView.dequeueReusableCellWithIdentifier(cellID, forIndexPath:indexPath)

Related

UISearchController crash when selected

I tried to implement a UISearchController into my ViewController. However, when I try to open up the Controller from a button it crashes the application and there is no error given to me from Xcode. I am using Backendless to store users and to retrieve them. I want to search through them.
Here is my code. I don't know what I am doing wrong :/ I would really appreciate the help.
import UIKit
protocol ChooseUserDelegate {
func chreatChatroom(withUser: BackendlessUser)
}
class ChooseUserViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating {
#IBOutlet weak var tableView: UITableView!
var delegate: ChooseUserDelegate!
var users: [BackendlessUser] = []
var filteredUsers = [BackendlessUser]()
var resultSearchController: UISearchController!
override func viewDidLoad() {
super.viewDidLoad()
loadUsers()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: UITableviewDataSorce
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
self.filteredUsers.removeAll(keepCapacity: false)
let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %#", searchController.searchBar.text!); let array = (self.users as NSArray).filteredArrayUsingPredicate(searchPredicate)
self.filteredUsers = array as! [BackendlessUser]
self.tableView.reloadData()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if resultSearchController.active
{
return self.filteredUsers.count
} else {
return users.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell?
if self.resultSearchController.active
{
let userFiltered = filteredUsers[indexPath.row]
cell!.textLabel?.text = userFiltered.name
} else {
let user = users[indexPath.row]
cell!.textLabel?.text = user.name
}
return cell!
}
//MARK: UITableviewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let user = users[indexPath.row]
delegate.chreatChatroom(user)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
self.dismissViewControllerAnimated(true, completion: nil)
}
//MARK: IBactions
#IBAction func cancelButtonPressed(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
//MARK: Load Backendless Users
func loadUsers() {
let whereClause = "objectId != '\(backendless.userService.currentUser.objectId)'"
let dataQuery = BackendlessDataQuery()
dataQuery.whereClause = whereClause
let dataStore = backendless.persistenceService.of(BackendlessUser.ofClass())
dataStore.find(dataQuery, response: { (users : BackendlessCollection!) -> Void in
self.users = users.data as! [BackendlessUser]
self.resultSearchController = UISearchController(searchResultsController: nil)
self.resultSearchController.searchResultsUpdater = self
self.resultSearchController.dimsBackgroundDuringPresentation = false
self.resultSearchController.searchBar.sizeToFit()
self.tableView.tableHeaderView = self.resultSearchController.searchBar
self.tableView.reloadData()
}) { (fault : Fault!) -> Void in
print("Error, couldnt retrieve users: \(fault)")
}
}
}
Your resultSearchController is nil before it is used. It's set in a closure that almost certainly sets it after it's needed when setting up the view. To fix it, just move this initialization code to something earlier like viewDidLoad():
self.resultSearchController = UISearchController(searchResultsController: nil)
self.resultSearchController.searchResultsUpdater = self
self.resultSearchController.dimsBackgroundDuringPresentation = false
self.resultSearchController.searchBar.sizeToFit()
self.tableView.tableHeaderView = self.resultSearchController.searchBar

How to set CustomTableView immediately (CoreData)

I have a TextField, Button and a TableView in ViewController
I press Button -> import Text to Data and also export to TableView
But it does not work
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
myTableView.reloadData()
}
#IBOutlet weak var txtClient: UITextField!
#IBAction func butNhap(sender: AnyObject) {
var newName = txtClient.text as String
var myDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var myContext: NSManagedObjectContext = myDelegate.managedObjectContext!
var myText: AnyObject = NSEntityDescription.insertNewObjectForEntityForName("Client", inManagedObjectContext: myContext)
myText.setValue(newName, forKey: "name")
txtClient.text = ""
}
#IBOutlet weak var myTableView: UITableView!
var exportArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
self.myTableView.delegate = self
self.myTableView.dataSource = self
myTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "myCell")
}
func export() -> [String] {
var myDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var myContext: NSManagedObjectContext = myDelegate.managedObjectContext!
var exportName = NSFetchRequest(entityName: "Client")
exportName.returnsObjectsAsFaults = false
var exportValue = myContext.executeFetchRequest(exportName, error: nil)
for result: AnyObject in exportValue! {
exportArray.insert((result.valueForKey("name") as! String), atIndex: 0)
}
return exportArray
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel?.text = exportArray[indexPath.row]
return cell
}
}
Create one custom UITableviewcell and give name and identifier it like "customtableCell", then on the respective view controller you have to register that custom cell,
let nibName = UINib(nibName: "customtableCell", bundle:nil)
tblConnect!.registerNib(nibName, forCellReuseIdentifier: "customtableCell")
After that on the cellForRowAtIndexPath use below type of code,
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let identifier = "customtableCell"
var tablecell: customtableCell!
if (tablecell == nil) {
tablecell = tableView.dequeueReusableCellWithIdentifier(identifier) as? customtableCell
}
return tablecell
}

Swift crashes after TableViewCell pressed

My app keeps crashing when I select the TableViewCell but it does not give me an error message. Hope some on can help. Below is the TableView Controller and the View Controller code. I have added the date into the cordite model and think it has something to do with that.
import UIKit
import CoreData
class DiveLogTableViewController: UITableViewController {
var myDivelog : Array<AnyObject> = []
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewDidAppear(animated: Bool) {
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext!
let freq = NSFetchRequest(entityName: "Divelog")
myDivelog = context.executeFetchRequest(freq, error: nil)!
tableView.reloadData()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "update" {
var selectedItem: NSManagedObject = myDivelog[self.tableView.indexPathForSelectedRow()!.row] as! NSManagedObject
let ADLVC: AddDiveLogViewController = segue.destinationViewController as! AddDiveLogViewController
ADLVC.divenumber = selectedItem.valueForKey("divenumber") as! String
ADLVC.ddate = selectedItem.valueForKey("ddate") as! NSDate
ADLVC.divelocation = selectedItem.valueForKey("divelocation") as! String
ADLVC.existingItem = selectedItem
}
}
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 {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return myDivelog.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let CellID: NSString = "Cell"
var cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(CellID as String) as! UITableViewCell
if let ip = indexPath as NSIndexPath? {
var data: NSManagedObject = myDivelog[ip.row] as! NSManagedObject
var ddate = data.valueForKey("ddate") as! NSDate
var diveloc = data.valueForKey("divelocation") as! String
var diveno = data.valueForKey("divenumber") as! String
cell.textLabel!.text = "#\(diveno)#\(diveloc)"
cell.detailTextLabel!.text = "\(ddate),location: \(diveloc)"
}
// Configure the cell...
return cell
}
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext!
if editingStyle == UITableViewCellEditingStyle.Delete {
if let tv = tableView as UITableView? {
context.deleteObject(myDivelog[indexPath.row] as! NSManagedObject)
myDivelog.removeAtIndex(indexPath.row)
tv.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
}
var error: NSError? = nil
if !context.save(&error) {
abort()
}
}
}
}
import UIKit
import CoreData
class AddDiveLogViewController: UIViewController {
#IBOutlet weak var textFieldDiveNumber: UITextField!
#IBOutlet weak var textFieldDiveLocation: UITextField!
#IBOutlet weak var textFieldDDate: UITextField!
var divenumber: String = ""
var divelocation: String = ""
var ddate = NSDate()
var datePickerView: UIDatePicker!
var existingItem: NSManagedObject!
override func viewDidLoad() {
super.viewDidLoad()
if (existingItem != nil) {
textFieldDiveNumber.text = divenumber
textFieldDiveLocation.text = divelocation
textFieldDDate.text = ddate.stringValue
}
// Do any additional setup after loading the view.
datePickerView = UIDatePicker()
datePickerView.datePickerMode = UIDatePickerMode.Date
var toolbar = UIToolbar(frame: CGRectMake(0, 0, datePickerView.frame.width, 44))
let OKButton = UIBarButtonItem(title: "OK", style: .Plain, target: self, action: "OKButtonTapped:")
toolbar.setItems([OKButton], animated: true)
self.textFieldDDate.inputView = datePickerView
self.textFieldDDate.inputAccessoryView = toolbar
}
#IBAction func saveTapped(sender: AnyObject) {
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let contxt: NSManagedObjectContext = appDel.managedObjectContext!
let en = NSEntityDescription.entityForName("Divelog", inManagedObjectContext: contxt)
if (existingItem != nil) {
existingItem.setValue(textFieldDiveNumber.text, forKey: "divenumber")
existingItem.setValue(textFieldDiveLocation.text, forKey: "divelocation")
existingItem.setValue(textFieldDDate.text.dateValue!, forKey: "ddate")
} else {
var newItem = Divelog(entity: en!, insertIntoManagedObjectContext: contxt)
newItem.divenumber = textFieldDiveNumber.text
newItem.divelocation = textFieldDiveLocation.text
newItem.ddate = textFieldDDate.text.dateValue!
}
contxt.save(nil)
self.navigationController?.popToRootViewControllerAnimated(true)
}
#IBAction func cancelTapped(sender: AnyObject) {
self.navigationController?.popToRootViewControllerAnimated(true)
}
func OKButtonTapped(sender: UIBarButtonItem) {
self.textFieldDDate.endEditing(true)
self.textFieldDDate.text = datePickerView.date.stringValue
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

Swift filter UITableView with out search bar

I have a UITableView that I want to filter based on a selection from slide panel view controller. This is the function that gets the returned value form the panel.
func itemSelected(type: Item) {
self.selectedItem = Item.title
delegate?.collapseSidePanels?()
}
Table view code.
var myData: Array<AnyObject> = []
var selectedItem:Array<AnyObject> = []
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellID: NSString = "Cell"
var Cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellID as String) as! UITableViewCell
var data: NSManagedObject = myData[indexPath.row] as! NSManagedObject
if tableView == selectedItem {
data = self.selectedItem[indexPath.row] as! NSManagedObject
} else
{
data = myData[indexPath.row] as! NSManagedObject
}
Cell.textLabel?.text = data.valueForKeyPath("itemname") as? String
var tt = data.valueForKeyPath("itemtype") as! String
Cell.detailTextLabel?.text = ("Item Type: \(tt)")
return Cell
}
I need to filter on the itemtype.
edit - Will not filter still so here is the full code for the tableViewController.
import UIKit
import CoreData
import Foundation
#objc
protocol tableViewControllerDelegate {
optional func toggleLeftPanel()
optional func toggleRightPanel()
optional func collapseSidePanels()
}
class tableViewController: UITableViewController, NSFetchedResultsControllerDelegate, SidePanelViewControllerDelegate {
var delegate: tableViewControllerDelegate?
var myData: Array<AnyObject> = []
var myFilteredData: Array<AnyObject> = []
#IBAction func leftTapped(sender: AnyObject) {
delegate?.toggleLeftPanel?()
}
// Use this to change table view to edit mode
// and to Change the title when clicked on.
// Make sure to have sender set as UIBarButtonItem
// or you can not change the title of the button.
var condition: Bool = true
#IBAction func buttonEdit(sender: UIBarButtonItem) {
if(condition == true) {
tableView.editing = true
sender.title = "Done"
condition = false
} else {
tableView.editing = false
sender.title = "Edit"
condition = true
}
}
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
var fetchedResultController: NSFetchedResultsController = NSFetchedResultsController()
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
// This is neeed when using panel view controller to show the bottom navbar.
self.navigationController?.setToolbarHidden(false, animated: true)
// ref app del
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
// Ref data
let context: NSManagedObjectContext = appDel.managedObjectContext!
let freq = NSFetchRequest(entityName: "Products")
myData = context.executeFetchRequest(freq, error: nil)!
}
override func viewDidAppear(animated: Bool) {
}
// 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 {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
if (self.myFilteredData.count != 0) {
return self.myFilteredData.count
} else {
return self.myData.count
}
}
func getFetchedResultController() -> NSFetchedResultsController {
fetchedResultController = NSFetchedResultsController(fetchRequest: NSFetchRequest(), managedObjectContext: managedObjectContext!, sectionNameKeyPath: nil, cacheName: nil)
return fetchedResultController
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellID: String = "Cell"
var cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellID as String) as! UITableViewCell
var data: NSManagedObject
if (self.myFilteredData.count != 0){
data = myFilteredData[indexPath.row] as! NSManagedObject
cell.textLabel?.text = data.valueForKeyPath("productname") as? String
var tt = data.valueForKeyPath("itemtype") as! String
cell.detailTextLabel?.text = ("Item J Type: \(tt)")
} else {
data = myData[indexPath.row] as! NSManagedObject
cell.textLabel?.text = data.valueForKeyPath("productname") as? String
var tt = data.valueForKeyPath("itemtype") as! String
cell.detailTextLabel?.text = ("Item Type: \(tt)")
}
return cell
}
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
let item: AnyObject = myData[sourceIndexPath.row]
myData.removeAtIndex(sourceIndexPath.row)
myData.insert(item, atIndex: destinationIndexPath.row)
}
// called when a row deletion action is confirmed
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
switch editingStyle {
case .Delete:
// remove the deleted item from the model
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext!
context.deleteObject(myData[indexPath.row] as! NSManagedObject)
myData.removeAtIndex(indexPath.row)
context.save(nil)
// remove the deleted item from the `UITableView`
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
default:
return
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "showProduct"){
let selectedIndexPath:NSIndexPath = self.tableView.indexPathForSelectedRow()!
let genView:genViewController = segue.destinationViewController as! genViewController
genView.row = selectedIndexPath.row
}
else if (segue.identifier == "addProduct"){
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func itemSelected(item: Type) {
var selectedType = item.title
delegate?.collapseSidePanels?()
for (key, value) in enumerate(self.myData) {
if (value.valueForKeyPath("itemtype") !== "selectedType") {
self.myFilteredData.append(value)
dump(myFilteredData)
} else {
// do nothing with it
}
}
tableView.reloadData()
}
}
Depending on however you want the data filtered, you could loop through myData in itemSelected(), find the elements that you want in your filtered list and save them in a new array (myFilteredData).
var myFilteredData: Array<AnyObject> = []
func itemSelected(type: Item) {
self.selectedItem = Item.title
delegate?.collapseSidePanels?()
for (key, value) in enumerate(self.myData) {
if (value.valueForKeyPath("itemtype") == "yourCondition") {
self.myFilteredData.append(value)
} else {
// do nothing with it
}
}
tableView.reloadData() // use tableView.reloadSections with rowAnimation for better effect.
}
You would then reload the tableview with tableView.reloadSections(_ sections: NSIndexSet,
withRowAnimation animation: UITableViewRowAnimation), which will trigger the cellForRowAtIndexPath function. Here, you would need to decide if you want to use myData or myFilteredData for the cell's labels.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
...
var data:NSManagedObject
if (self.myFilteredData.count != 0) {
data = myFilteredData[indexPath.row] as! NSManagedObject
} else {
data = myData[indexPath.row] as! NSManagedObject
}
...
}
Also, don't forget to modify the numberOfRowsInSection function to return the size of the array you are populating the tableView with.
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (self.myFilteredData.count != 0) {
return self.myFilteredData.count
} else {
return self.myData.count
}
}

Custom UITableViewCell causing UISearchBar to crash

I have a tableView with a UISearchBar set up. Every time the user starts typing in the search bar the app crashes. I discovered that the problem is that I'm using a custom tableViewCell (when I tried running the app with the default tableViewCell it didn't crash and worked fine.). Any ideas on how to fix this? Thanks.
Here's my code:
import UIKit
import CoreData
class KeepTableViewController: UITableViewController, UISearchBarDelegate{
#IBOutlet weak var searchBar: UISearchBar!
var filteredQuotes = [AnyObject]()
var keptQuotes = [NSManagedObject]()
override func viewDidLoad() {
super.viewDidLoad()
searchBar.delegate = self
searchBar.showsScopeBar = true
tableView.rowHeight = UITableViewAutomaticDimension
getCoreData()
searchDisplayController?.searchResultsTableView.registerClass(QuoteyTableViewCell.self, forCellReuseIdentifier: "Cell")
}
func getCoreData(){
var appDel : AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
var context : NSManagedObjectContext = appDel.managedObjectContext!
var req : NSFetchRequest = NSFetchRequest(entityName: "KeptQuotes")
var error : NSError?
let fetchedResults = context.executeFetchRequest(req, error: &error) as [NSManagedObject]?
if let results = fetchedResults {
keptQuotes = results
}else{
println("Could not fetch \(error), \(error!.userInfo)")
}
tableView.reloadData()
}
#IBAction func cancelPressed(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil) //dismisses the freakin view
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
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 {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
if tableView == self.searchDisplayController?.searchResultsTableView {
return filteredQuotes.count
}else{
return keptQuotes.count
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : QuoteyTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as QuoteyTableViewCell
var entry : NSManagedObject
if tableView == self.searchDisplayController!.searchResultsTableView{
entry = filteredQuotes[indexPath.row] as NSManagedObject
}else{
entry = keptQuotes[indexPath.row] as NSManagedObject!
}
cell.authorLabel.text = entry.valueForKey("author") as String!
cell.quoteTextLabel.text = entry.valueForKey("quote") as String!
cell.quoteTextLabel.sizeToFit()
cell.selectionStyle = UITableViewCellSelectionStyle.None
return cell
}
func filterContentForSearchText(searchText: String) {
var qs : NSArray = keptQuotes
let predicate = NSPredicate(format: "quote contains[c] %# OR author contains[c] %#", searchText, searchText)
filteredQuotes = qs.filteredArrayUsingPredicate(predicate!)
println(filteredQuotes)
}
func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchString searchString: String!) -> Bool {
self.filterContentForSearchText(searchString)
return true
}
func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchScope searchOption: Int) -> Bool {
self.filterContentForSearchText(searchDisplayController!.searchBar.text)
return true
}
}
Custom TableViewCell:
import UIKit
class QuoteyTableViewCell: UITableViewCell {
#IBOutlet weak var authorLabel: UILabel!
#IBOutlet weak var quoteTextLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
quoteTextLabel.textColor = UIColor(rgba: "#293B50")
authorLabel.textColor = UIColor(rgba: "#A4ACB5")
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
I came across the same problem as yours too not too long ago. What I did to make mine work was instead of laying out my custom cell directly in the prototype cell, I created a separate .xib file for it, set the prototype cells in my tableViewController to 0 and did
let regularCell = UINib(nibName: "Cell", bundle: nil)
self.searchDisplayController!.searchResultsTableView.registerNib(regularCell, forCellReuseIdentifier: "Cell")

Resources