如何解决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,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)")
}
}
}
}
最终,在应用程序中执行搜索时,应该触发输出到控制台,而这不会发生。不是输出到控制台,而是切换键盘大小写,字母变为大写。我将不胜感激您的帮助、建议和批评! :)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。