swift - Main.storyboard/Controller 和 searchBar 中的问题接线委托
问题描述
今天遇到一个问题。我在TodoListViewController.swift中编写代码,但searchBar.gelegate = self
没有任何效果。还尝试将委托连接到Main.storyboard,但没有任何效果。这是TodoListViewController.swift代码:
import UIKit
import CoreData
class TodoListViewController: UITableViewController {
@IBOutlet weak var searchBar: UISearchBar!
var itemArray = [Item]()
let dataFilePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// In Main.storyboard was set-up searchBar.delegate = self
searchBar.delegate = self
print(dataFilePath)
loadItems()
}
//MARK: - Tableview 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
//Then sets cell of indexPath text = lists value of index path
//Ternary operator =>
// value = condifition ? valueTrue : valueFalse
cell.accessoryType = item.done ? .checkmark : .none
return cell
}
// when we click on cell
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
itemArray[indexPath.row].done = !itemArray[indexPath.row].done
saveItems()
tableView.deselectRow(at: indexPath, animated: true)
}
//MARK: - Add New Items
@IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
var textField = UITextField()
let alert = UIAlertController(title: "Add New Todoey Item", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "Add Item", style: .default) { (action) in
// what will happen once the user clicks the Add Item button on our UIAlert.
// handle an optional string that will never be nil (here). Handle value textField.text! below.
if textField.text == "" {
textField.placeholder = "Please enter text"
self.present(alert, animated: true, completion: nil)
} else {
let newItem = Item(context: self.context)
newItem.title = textField.text!
newItem.done = false
self.itemArray.append(newItem)
self.saveItems()
}
}
alert.addTextField { (alertTextField) in
alertTextField.placeholder = "Create new item"
textField = alertTextField
}
alert.addAction(action)
// adding cancel action.
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(cancelAction)
// to make the Add Item button bold and not Cancel Action.
alert.preferredAction = action
present(alert, animated: true, completion: nil)
}
//MARK: - Model Manipulations Method
func saveItems() {
do {
try context.save()
} catch {
print("Error saving context \(error)")
}
self.tableView.reloadData()
}
func loadItems() {
let request : NSFetchRequest<Item> = Item.fetchRequest()
do {
itemArray = try context.fetch(request)
} catch {
print("Error fetching data context \(error)")
}
self.tableView.reloadData()
}
}
//MARK: - Search Bar Methods
extension TodoListViewController: UISearchBarDelegate {
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
print("searchText \(searchText)")
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
let request : NSFetchRequest<Item> = Item.fetchRequest()
print("Print: \(searchBar.text!)")
}
}
这里AppDelegate.swift:
//
// AppDelegate.swift
// Destini
//
// Created by Philipp Muellauer on 01/09/2015.
// Copyright (c) 2015 London App Brewery. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
return true
}
func applicationWillTerminate(_ application: UIApplication) {
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "DataModel")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
最终,当在应用程序中执行搜索时,应该触发到控制台的输出,这不会发生。不是输出到控制台,而是切换键盘大小写,字母变为大写。我将不胜感激您的帮助、建议和批评!:)
解决方案
推荐阅读
- node.js - 使用 Node js 在 LAN 上进行点对点连接
- java - spring sleuth - 标签和行李之间的区别
- rabbitmq - 如何关闭 Rabbitmq 连接
- css - 如何为离子可选项目添加颜色
- java - 如何有效地使用流
- php - 如何在 Magento 的产品名称中附加 Sku。?
- javascript - Mongoose:按对象 id 分组并推入一个数组,按 createdAt 排序,填充所有对象并对其进行分页
- ios - 从 CVPixelBufferRef 构造 CAMetalLayer
- sql - Oracle - 日期格式验证
- beautifulsoup - Python BeautifulSoup 从类中获取文本