Swift 使用textfield委托响应textfield中的即时更改

Swift 使用textfield委托响应textfield中的即时更改,swift,core-data,uitextfield,fetch,uitextfielddelegate,Swift,Core Data,Uitextfield,Fetch,Uitextfielddelegate,我的swift代码现在使用textfield委托更改标签中显示的内容。问题是,只有当用户输入一个数字,然后将其删除时,标签才会更改。正如您在下面的gif中所看到的。我想做的就是当用户输入1时,kim kardashian出现在标签上。现在它可以做到了,但我必须使用ener 1,然后将其从文本字段中删除,直到kim kardashian出现在标签上 导入UIKit 导入CoreData 类ViewController:UIViewController、UIExtFieldDelegate{ @I

我的swift代码现在使用textfield委托更改标签中显示的内容。问题是,只有当用户输入一个数字,然后将其删除时,标签才会更改。正如您在下面的gif中所看到的。我想做的就是当用户输入1时,kim kardashian出现在标签上。现在它可以做到了,但我必须使用ener 1,然后将其从文本字段中删除,直到kim kardashian出现在标签上

导入UIKit
导入CoreData
类ViewController:UIViewController、UIExtFieldDelegate{
@IBVAR标签名称:UILabel!
@IBOutlet var enterT:UITextField!
惰性变量上下文=(UIApplication.shared.delegate为!AppDelegate)。persistentContainer.viewContext
重写func viewDidLoad(){
super.viewDidLoad()
OpenDatabase()
enterT.delegate=self
}
func笑话(索引:Int){
let fetchRequest=NSFetchRequest(entityName:“用户”)
fetchRequest.predicate=NSPredicate(格式:“idx==%d”,Int32(索引))
做{
如果let user=try context.fetch(fetchRequest).first{
labelName.text=user.username
}
}抓住{
打印(“无法获取\(错误)”)
}
}
func opendatabase()
{
让名字=[“金·卡戴珊”、“杰西卡·贝尔”、“海莉·里恩哈特”]
因为我在0..Bool{
//返回NO以不更改文本
打印(“在输入字符时调用此方法”)
guard let index=Int(textField.text!)否则{
//显示有关无效文本的警报
返回真值
}
笑话(at:index)
返回真值
}}

如果您使用函数
touchsbegind()
并创建文本字段
。resignFirstResponder
,您还可以在其中添加更新函数。

您可以尝试使用此函数

textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)


textField.text
在对
textField
=进行任何更改之前提供文本,即之前输入的
文本
。您还需要向其添加
替换字符串
。在
textField
中输入的是新的
文本

因此,
UITextFieldDelegate
方法
textField(\uu:shouldChangeCharactersIn:replacementString)
应该如下所示:

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 text = (textField.text as? NSString)?.replacingCharacters(in: range, with: string), let index = Int(text) else { //here....
        // display an alert about invalid text
        return true
    }
    joke(at: index )
    return true
}

我应该在textfieldidchange中输入什么?
应该更改此方法的内容和check@YaoSmith删除
shouldChangeCharacters中的
并将其所有代码复制到
textFieldDidChange
func textFieldDidChange(_ textField: UITextField) {

}
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 text = (textField.text as? NSString)?.replacingCharacters(in: range, with: string), let index = Int(text) else { //here....
        // display an alert about invalid text
        return true
    }
    joke(at: index )
    return true
}