使用新数据搜索和重新加载TableView记录

时间:2016-10-29 07:22:01

标签: xcode uitableview search core-data tableviewcell

我正在开发IOS应用程序,使用Xcode 8和swift 3.我的应用程序有tableView中显示的项目列表我想按日期搜索特定项目"使用datePicker"。这些项目存储在Core数据库中。

这是我的代码。它搜索得很好但我在显示搜索数据方面遇到了麻烦。

@IBAction func searchButton(_ sender: AnyObject) {

    if(dateText.text != nil){
        let request = NSFetchRequest <NSFetchRequestResult> (entityName : "Expense_Table")
        request.returnsObjectsAsFaults = false
      request.predicate = NSPredicate(format: "expenseDate = %@", dateText.text!)

     do {
            let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell") as! customeCell

            let result = try self.context.fetch(request)

            if (result.count > 0) {
                for results in result as! [NSManagedObject]
                {
                first = results.value(forKey : "exoenseName") as! String
                last  = results.value(forKey : "expenseAmount") as! Double
                second = results.value(forKey: "expenseDate") as! String
                    //print the data in the Output section of Xcode
                    print (second)
                    print (String (last))
                    print (first)

                    // save data in the cell of the tableView
                    cell.dateText.text = second
                    cell.amounttext.text = String (last)
                    cell.nameText.text = first

                    tableView.addSubview(cell)// this method print result over the table view data 


                }
                tableView.reloadData()


            }
        }catch{}



        }
}

1 个答案:

答案 0 :(得分:0)

您误解了模型 - 视图 - 控制器模式。

  • 在班级

    的顶层创建模型
    searchButton
  • reloadData方法中,控制器将数据加载到模型中并调用@IBAction func searchButton(_ sender: AnyObject) { if dateText.text != nil { let request = NSFetchRequest <NSFetchRequestResult> (entityName : "Expense_Table") request.returnsObjectsAsFaults = false request.predicate = NSPredicate(format: "expenseDate = %@", dateText.text!) do { expenses = try self.context.fetch(request) as! [NSManagedObject] tableView.reloadData() } catch { print(error) } } }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)  as! customeCell
      let expense = expenses[indexPath.row]
      let first = expense.value(forKey : "exoenseName") as! String
      let last  = expense.value(forKey : "expenseAmount") as! Double
      let second = expense.value(forKey: "expenseDate") as! String
      // save data in the cell of the tableView
      cell.dateText!.text = second
      cell.amounttext!.text = String(last)!
      cell.nameText!.text = first
    
      return cell
    }
    
  • 在cellForRowAtIndexPath中,视图已更新

    camera.setNearClip(10);