Swift过滤UITableView没有搜索栏

时间:2015-04-10 03:01:47

标签: uitableview swift ios8 xcode6.3

我有一个UITableView,我想根据幻灯片面板视图控制器中的选择进行过滤。这是从面板中获取返回值的函数。

func itemSelected(type: Item) {

    self.selectedItem = Item.title

    delegate?.collapseSidePanels?()
}

表格视图代码。

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
}

我需要过滤itemtype。

编辑 - 不会过滤,所以这里是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() 
}

}

1 个答案:

答案 0 :(得分:2)

根据您希望过滤的数据,您可以在myData中循环浏览itemSelected(),在过滤后的列表中找到所需的元素并将其保存在新数组中{{1} })。

myFilteredData

然后,您将使用tableView.reloadSections(_ sections: NSIndexSet, withRowAnimation animation: UITableViewRowAnimation)重新加载tableview,这将触发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. } 功能。在这里,您需要决定是否要将cellForRowAtIndexPathmyData用于单元格的标签。

myFilteredData

另外,不要忘记修改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 } ... } 函数以返回填充tableView的数组的大小。

numberOfRowsInSection