2017-08-16 60 views
0

我正在製作帶有核心數據的TableViewController。實際上,用戶可以將新項目添加到表格視圖中,這些項目保存在覈心數據中。視圖將顯示聯繫人列表。 一切工作正常,但我無法讓搜索欄工作。我嘗試了很多,但我對swift很陌生,這是我的第一個應用程序。請告訴我應該將哪些內容添加到我的代碼中?帶有核心數據的TableViewController中的搜索欄

class ContactsViewController: UITableViewController { 

    @IBOutlet var searchBar: UISearchBar! 
    var contacts: [NSManagedObject] = [] 



    override func viewDidLoad() { 
     super.viewDidLoad() 
     fetch() 
     tableView.reloadData() 

    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

    //MARK: - Data Source 

    func fetch() { 
     guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } 
     let managedObjectContext = appDelegate.persistentContainer.viewContext 
     let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName:"Contact") 
     do { 
      contacts = try managedObjectContext.fetch(fetchRequest) as! [NSManagedObject] 
     } catch let error as NSError { 
      print("Could not fetch. \(error)") 
     } 
    } 

    func save(name: String, phoneNumber: String, dataUltimei: String) { 
     guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } 
     let managedObjectContext = appDelegate.persistentContainer.viewContext 
     guard let entity = NSEntityDescription.entity(forEntityName:"Contact", in: managedObjectContext) else { return } 
     let contact = NSManagedObject(entity: entity, insertInto: managedObjectContext) 
     contact.setValue(name, forKey: "name") 
     contact.setValue(phoneNumber, forKey: "phoneNumber") 
     contact.setValue(dataUltimei, forKey: "dataUltimei") 
     do { 
      try managedObjectContext.save() 
      self.contacts.append(contact) 
     } catch let error as NSError { 
      print("Couldn't save. \(error)") 
     } 
    } 

    func update(indexPath: IndexPath, name:String, phoneNumber: String, dataUltimei: String) { 
     guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } 
     let managedObjectContext = appDelegate.persistentContainer.viewContext 
     let contact = contacts[indexPath.row] 
     contact.setValue(name, forKey:"name") 
     contact.setValue(phoneNumber, forKey: "phoneNumber") 
     contact.setValue(dataUltimei, forKey: "dataUltimei") 
     do { 
      try managedObjectContext.save() 
      contacts[indexPath.row] = contact 
     } catch let error as NSError { 
      print("Couldn't update. \(error)") 
     } 
    } 

    func delete(_ contact: NSManagedObject, at indexPath: IndexPath) { 
     guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } 
     let managedObjectContext = appDelegate.persistentContainer.viewContext 
     managedObjectContext.delete(contact) 
     contacts.remove(at: indexPath.row) 
    } 

    override func numberOfSections(in tableView: UITableView) -> Int { 
     return 1 
    } 

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 


     return contacts.count 

    } 




    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 


     let cell = tableView.dequeueReusableCell(withIdentifier: "ContactCell", for: indexPath) 

     var contact = contacts[indexPath.row] 

     if isSearching { 

      contact = contacts[indexPath.row] 

     } 
     else { 

      contact = contacts[indexPath.row] 

     } 

     cell.textLabel?.text = contact.value(forKey:"name") as? String 

     } 
     return cell 
    } 


    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { 
     if editingStyle == .delete { 

      do { 

       let contact = contacts[indexPath.row] 
       delete(contact, at: indexPath) 
       fetch() 
       tableView.reloadData() 


      } catch let error as NSError { 
       print("Could not save. \(error), \(error.userInfo)") 
      } 
     } 
    } 

    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { 
     // Return false if you do not want the specified item to be editable. 
     return true 
    } 


    @IBAction func unwindToContactList(segue: UIStoryboardSegue) { 
     if let viewController = segue.source as? AddContactViewController { 
      guard let name: String = viewController.nameTextField.text, let phoneNumber: String = viewController.phoneNumberTextField.text, let dataUltimei: String = viewController.tabel.text else { return } 
      if name != "" && phoneNumber != "" { 
       if let indexPath = viewController.indexPathForContact { 
        update(indexPath: indexPath, name: name, phoneNumber: phoneNumber, dataUltimei: dataUltimei) 
       } else { 
        save(name:name, phoneNumber:phoneNumber, dataUltimei:dataUltimei) 
       } 
      } 
      tableView.reloadData() 
     } else if let viewController = segue.source as? ContactDetailViewController { 
      if viewController.isDeleted { 
       guard let indexPath: IndexPath = viewController.indexPath else { return } 
       let contact = contacts[indexPath.row] 
       delete(contact, at: indexPath) 
       tableView.reloadData() 
      } 
     } 
    } 

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
     if segue.identifier == "contactDetailSegue" { 
      guard let navViewController = segue.destination as? UINavigationController else { return } 
      guard let viewController = navViewController.topViewController as? ContactDetailViewController else { return } 
      guard let indexPath = tableView.indexPathForSelectedRow else { return } 
      let contact = contacts[indexPath.row] 
      viewController.contact = contact 
      viewController.indexPath = indexPath 
     } 
    } 

} 
+0

嗨,歡迎來到SO。請添加有關不工作的含義。您也可以參考[如何創建一個最小的,可驗證的示例](https://stackoverflow.com/help/mcve),以獲得更好的使用本站點的結果。祝你好運! – theFunkyEngineer

回答

0

添加以下功能:

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { 
    if !searchText.isEmpty { 
     var predicate: NSPredicate = NSPredicate() 
     predicate = NSPredicate(format: "name contains[c] '\(searchText)'") 
     guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } 
     let managedObjectContext = appDelegate.persistentContainer.viewContext 
     let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName:"Contact") 
     fetchRequest.predicate = predicate 
     do { 
      contacts = try managedObjectContext.fetch(fetchRequest) as! [NSManagedObject] 
     } catch let error as NSError { 
      print("Could not fetch. \(error)") 
     } 
    } 
    tableView.reloadData() 
} 

添加UISearchBarDelegate和UISearchDisplayDelegate象下面這樣:

class ViewController: UIViewController, UISearchBarDelegate, UISearchDisplayDelegate 

並添加搜索欄委託在viewDidLoad中:

searchBar.delegate=self 
+0

非常感謝!我做了你所說的,它沒有崩潰,但是當我輸入搜索欄時,它什麼也沒有顯示 – Lucian

+0

也許你正在尋找不存在的名字。請檢查。 –

+0

是的,我正在尋找聯繫人的名字。我應該添加什麼功能才能工作? – Lucian