Search code examples
swiftcore-datauitextfieldfetchuitextfielddelegate

use textfield delegate to respond to immediate change in textfield


My swift code right now uese textfield delegate to change what is display in a label. The problem is the label only changes when the user enters a number and then deletes it. As you can see in the gif below. All I want to do is whent he user enters 1 is for kim kardashian appears on the label. Right now it does it but I have to ener 1 then delete it from the textfield and only then kim kardashian appears on the label.

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
}}

Solution

  • textField.text gives the text before making any changes to the textField=, i.e. the previously entered text. You need to add the replacementString to it as well. It is the new text that is being entered in the textField.

    So, the UITextFieldDelegate method textField(_: shouldChangeCharactersIn: replacementString) should look like,

    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
    }