我现在的快速代码是通过uese文本字段委托来更改标签中显示的内容。问题在于,仅当用户输入数字然后将其删除时,标签才会更改。如下面的gif所示。我要做的就是用户输入1时kim kardashian出现在标签上。现在它可以了,但是我必须先生成1,然后从文本字段中删除它,然后kim kardashian才会出现在标签上。
import UIKit
import CoreData
class ViewController: UIViewController,UITextFieldDelegate {
@IBOutlet var labelName : UILabel!
@IBOutlet var enterT : UITextField!
lazy var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
override func viewDidLoad() {
super.viewDidLoad()
openDatabse()
enterT.delegate = self
}
func joke(at index : Int) {
let fetchRequest = NSFetchRequest<Users>(entityName: "Users")
fetchRequest.predicate = NSPredicate(format: "idx == %d",Int32(index))
do {
if let user = try context.fetch(fetchRequest).first {
labelName.text = user.username
}
} catch {
print("Could not fetch \(error) ")
}
}
func openDatabse()
{
let names = ["kim kardashian","jessica biel","Hailey Rienhart"]
for i in 0..<names.count {
let newUser = Users(context: context)
newUser.username = names[i]
newUser.idx = Int32(i + 1)
}
print("Storing Data..")
do {
try context.save()
} catch {
print("Storing data Failed",error)
}
}
func textField(_ textField: UITextField,shouldChangeCharactersIn range: NSRange,replacementString string: String) -> Bool {
// return NO to not change text
print("While entering the characters this method gets called")
guard let index = Int(textField.text!) else {
// display an alert about invalid text
return true
}
joke(at: index )
return true
}}