uitableview - 没有搜索栏的 Swift 过滤器 UITableView

标签 uitableview swift ios8 xcode6.3

我有一个 UITableView,我想根据滑动面板 View Controller 中的选择对其进行过滤。这是从面板获取返回值的函数。

func itemSelected(type: Item) {

    self.selectedItem = Item.title

    delegate?.collapseSidePanels?()
}

TableView 代码。

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
}

我需要过滤项目类型。

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

最佳答案

根据您希望过滤数据的方式,您可以在 itemSelected() 中循环遍历 myData,在过滤列表中找到您想要的元素并将它们保存在一个新数组 (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.
}

然后您将使用 tableView.reloadSections(_ sections: NSIndexSet, withRowAnimation animation: UITableViewRowAnimation) 重新加载 TableView ,这将触发 cellForRowAtIndexPath 函数。在这里,您需要决定是否要对单元格标签使用 myDatamyFilteredData

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
    }

    ...
}

此外,不要忘记修改 numberOfRowsInSection 函数以返回您用来填充 tableView 的数组的大小。

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if (self.myFilteredData.count != 0) {
        return self.myFilteredData.count
    } else {
        return self.myData.count
    }
}

关于uitableview - 没有搜索栏的 Swift 过滤器 UITableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29552628/

相关文章:

ios - 许多图像请求后 PHImageManager 崩溃

ios - 访问从 XIB 实例化的 View subview 的最佳方式?

ios - 如何实现自定义键盘的设置包?

ios - 重新加载数据后,UITableView 中的图片随机移动

ios - UITableViewCell 不显示 subview UITextView

ios - 在 UITableView 自定义单元格中的元素上点击手势

swift - 更改枚举的功能

ios - 此 bundle 无效。键 CFBundleShortVersionString 的值必须包含..Xcode Sticker app

iphone - 如何使用 RaptureXML 和 AFNetworking 在 UITableView 上动态显示解析的 XML 内容?

ios - Swift 4 - 音板应用程序 - 以编程方式将多个按钮标签分配给一个按钮?