简体   繁体   English

我无法从UISearchBar获取文本

[英]I'm having trouble getting the text from a UISearchBar

i tried to put searchBar above my table but code not worked with me 我试图将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()
            }
        }
    }
}

The problem with Do-Catch the Solution should be Do-Catch解决方案的问题应该是

do {
       itemArray = try context.fetch(request)
    } catch { print("Error fetching data from request\(error)")
    }
        tableView.reloadData()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我无法使该CA动画正常工作 - I'm having trouble getting this CA animation to work 无法显示UISearchBar的结果 - Having trouble showing results of UISearchBar 我无法让我的本地通知在 xcode 模拟器上的设定时间显示 - I'm having trouble getting my local notification to show up at the set time on xcode simulator 我无法根据与谓词的关系从核心数据中获取实体 - I'm having trouble fetching entities from core data based on relationships with predicates 我在从php文件中的应用程序接收注册信息时遇到麻烦,无法将该信息插入MSQL数据库中 - I'm having trouble receiving the registration information from the app in my php file to insert that information into the MSQL database 无法通过JSON调用获取日期 - Having trouble getting the date from a JSON call 我无法调整表格视图单元格的大小 - I'm having trouble resizing a table view cell 我在mapView中添加多个标记时遇到麻烦 - i'm having a trouble adding multiple markers in a mapView 我在Xcode 6中使用多个UIImageViews遇到麻烦 - I'm having trouble using multiple UIImageViews in Xcode 6 我在自定义 UITableViewCell 中以编程方式设置布局约束时遇到问题 - I'm having trouble with programmatically setting layout constraints in a custom UITableViewCell
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM