我试图将searchBar放在桌子上方,但是代码对我不起作用
import UIKit
import CoreData
class ToDoListViewController: UITableViewController {
var itemArray = [Item]()
var selectedCategory : Category?{
didSet {
loadItems()
}
}
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
override func viewDidLoad() {
super.viewDidLoad()
print(FileManager.default.urls(for: .documentDirectory, in: .userDomainMask))
}
// MARK - Table View DataSource Methods
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ToDoItemCell", for: indexPath)
let item = itemArray[indexPath.row]
cell.textLabel?.text = item.title
cell.accessoryType = item.done ? .checkmark : .none
return cell
}
// MARK - Table View Delegate Methods
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
itemArray[indexPath.row].done = !itemArray[indexPath.row].done
saveItems()
tableView.deselectRow(at: indexPath, animated: true)
}
@IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
var textField = UITextField()
let alert = UIAlertController(title: "Add New To Do List Item", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "Add Item", style:.default) { (action) in
// This will happend when the user clicks the Add Item on our add UIAlert
let newItem = Item(context: self.context)
newItem.title = textField.text!
newItem.done = false
newItem.parentCategory = self.selectedCategory
self.itemArray.append(newItem)
self.saveItems()
}
alert.addTextField { (alertTextField) in
alertTextField.placeholder = "Create New Item"
textField = alertTextField }
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
//MARK: - Data Manipulation Methods
func saveItems(){
do {
try context.save()
} catch {print("Error saving context \(error)") }
self.tableView.reloadData()
}
func loadItems(with request: NSFetchRequest<Item> = Item.fetchRequest(), with predicate: NSPredicate? = nil){
let categoryPredicate = NSPredicate(format: "parentCategory.name MATCHES %@", selectedCategory!.name!)
if let addtionalPredicate = predicate {
request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [categoryPredicate,addtionalPredicate])
}else {
request.predicate = categoryPredicate
}
do {
itemArray = try context.fetch(request)
} catch { print("Error fetching data from request\(error)")
tableView.reloadData()
}
}
}
// MARK: - Search Bar Methods
extension ToDoListViewController : UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
let request : NSFetchRequest<Item> = Item.fetchRequest()
let predicate = NSPredicate(format: "title CONTAINS[cd] %@", searchBar.text!)
request.sortDescriptors = [NSSortDescriptor(key: "title", ascending: true)]
loadItems(with: request, with: predicate)
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text?.count == 0 {
loadItems()
DispatchQueue.main.async {
searchBar.resignFirstResponder()
}
}
}
}
最佳答案
抓捕问题
解决方案应该是
do {
itemArray = try context.fetch(request)
} catch { print("Error fetching data from request\(error)")
}
tableView.reloadData()
关于ios - 我无法从UISearchBar获取文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50405496/