所以,这里是新功能,学习Swift 5.1,我正在研究一个简单的待办事项清单。除了UITextFieldDelegate之外,其他所有东西都在工作。这是我的代码:
import UIKit
import CoreData
class ViewController: UIViewController, UITextFieldDelegate, UITableViewDelegate, UITextFieldDelegate {
@IBOutlet weak var table: UITableView!
var itemName: [NSManagedObject] = []
override func viewDidLoad() {
super .viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
var titleTextField: UITextField!
func titleTextField(textfield: UITextField) {
titleTextField = textfield
titleTextField.placeholder = "Item Name"
}
@IBAction func addButton(_ sender: Any) {
let alert = UIAlertController(title: "Add Item", message: "Item Name", preferredStyle: .alert)
let addAction = UIAlertAction(title: "Save", style: .default, handler: self.save)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(addAction)
alert.addAction(cancelAction)
alert.addTextField(configurationHandler: titleTextField)
self.present(alert, animated: true, completion: nil)
}
func save(alert: UIAlertAction!) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let entity =
NSEntityDescription.entity(forEntityName: "Title", in: context)!
let theTitle = NSManagedObject(entity: entity, insertInto: context)
theTitle.setValue(titleTextField.text, forKey: "title")
do
{
try context.save()
itemName.append(theTitle)
}
catch{
print("There was an error saving")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemName.count
}
func tableView(_ tableView:UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let title = itemName[indexPath.row]
let cell =
tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = title.value(forKey: "Title") as? String
return cell
}
在第4行(ViewController类)中,出现此错误:
“'ViewController'与协议'UITextFieldDelegate的冗余一致性”
我连接了2个导航控制器。
答案 0 :(得分:1)
您两次符合UITextFieldDelegate
,应该是
class ViewController: UIViewController, UITableViewDelegate, UITextFieldDelegate {
对于表视图也不要忘记UITableViewDataSource