Home > database >  Storyboard, Event listener when UItextfield.text value is changed from button action
Storyboard, Event listener when UItextfield.text value is changed from button action

Time:11-22

UITextFieldDelegate method only works if we enter the data to textfield through the keyboard. But we I change the value of textfield. text from any button action none of its delegate methods is triggering. I have also tried to add the objective fun to listen for value change but they also only work when textfield received input from the keyboard.

     override func viewDidLoad() {
           super.viewDidLoad() 
           txtMinute.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
       }

       @objc func textFieldDidChange(_ textField: UITextField) {
            print(textField.text)
            enableEditButton()
        }

       @IBAction func change_minutes(_ sender: Any) {
        
           txtMinute.text = "123"
        
       }

Any suggestion on how to list change in for textfield on button action?

CodePudding user response:

Try the following:

override func viewDidLoad() {
    super.viewDidLoad()
    txtMinute.delegate = self
}

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    guard let oldText = textField.text, let range = Range(range, in: oldText) else {
        return true
    }
    
    let newText = oldText.replacingCharacters(in: range, with: string)
    print(newText)
    return true
}

CodePudding user response:

TextField Delegate Methods only called if you giving input through Keyboard,Suppose if you want those Delegate methods to be called while using custom NumPad you need to call Manually Like Below

@IBAction func change_minutes(_ sender: Any) {

    if let selectedRange = txtMinute.selectedTextRange {
            let range=txtMinute.rangeFromTextRangeForInsertion(textRange: selectedRange)
            txtMinute.delegate?.textField?(txtMinute, shouldChangeCharactersIn: range, replacementString: sender.titleLabel?.text ?? "")       
        }
 }
    
   }

 Extension UITextFieldDelegate{
 func rangeFromTextRangeForInsertion(textRange:UITextRange) -> NSRange {
        let cursorPosition = self.offset(from: self.beginningOfDocument, to: textRange.start)
        let length = self.offset(from: textRange.start, to: textRange.end)
        
        return NSMakeRange(cursorPosition, length)
    }
}

    //Your TextField Delegate Method
extension ViewController:UITextFieldDelegate{
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            enableEditButton()
            return true
  }
}
  • Related