使用文本字段委托响应文本字段中的立即更改

问题描述 投票:-1回答:3

我现在的快速代码是通过uese文本字段委托来更改标签中显示的内容。问题在于标签仅在用户输入数字然后将其删除时才会更改。如下面的gif所示。我要做的就是用户输入1时kim kardashian出现在标签上。现在它可以了,但是我必须启用1,然后从文本字段中删除它,然后kim kardashian才会出现在标签上。

enter image description here

  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
}}
swift core-data uitextfield fetch uitextfielddelegate
3个回答
1
投票

您可以尝试这个,

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

func textFieldDidChange(_ textField: UITextField) {

}

0
投票

如果使用功能touchesBegan()并设置文本字段.resignFirstResponder,也可以在其中添加更新功能。


0
投票

textField.text在更改textField =,即先前输入的text之前给出文本。您还需要添加replacementString。在text中输入的是textField

所以UITextFieldDelegate方法textField(_: 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 _ = Int(text) else { //here....
        // display an alert about invalid text
        return true
    }
    joke(at: index )
    return true
}
© www.soinside.com 2019 - 2024. All rights reserved.