简体   繁体   中英

How to trigger editchanged event of textbox on button click in swift4

I am aware of editchanged event of a textbox and it is working properly when I change the text in textbox using mac's keypad but I have made numeric buttons and when I change text using buttons the editchanged of textbox is not triggered.

This is my button event

@IBAction func digitbuttonpress(_ sender: UIButton)
{
    if(text1.isFirstResponder)
    {
        text1.text = text1.text! + sender.titleLabel!.text!
    }
    else if(text2.isFirstResponder)
    {
        text2.text = text2.text! + sender.titleLabel!.text!
    }
}

You can make the code inside editingChanged in a function say sharedTrigger and call it from anywhere

@IBAction func digitbuttonpress(_ sender: UIButton)
{
    if(text1.isFirstResponder)
    {
        text1.text = text1.text! + sender.titleLabel!.text!
    }
    else if(text2.isFirstResponder)
    {
        text2.text = text2.text! + sender.titleLabel!.text!
    }

    self.sharedTrigger()
}

You cannot programmatically trigger the editChanged event, that event happens when user edits the textField (not textBox).

Whatever you want to do after the event, you will have to call it programmatically from digitbuttonpress :

@IBAction func digitbuttonpress(_ sender: UIButton) {
    if(text1.isFirstResponder) {
        text1.text = text1.text! + sender.titleLabel!.text!
        // explicitly call the handler
        self.text1EditChangedHandler()
    } else if(text2.isFirstResponder) {
        text2.text = text2.text! + sender.titleLabel!.text!
        // explicitly call the handler
        self.text2EditChangedHandler()
    }
}

You don't need to write a new function - you can call your existing edit changed function from code:

@IBAction func digitbuttonpress(_ sender: UIButton) {
    if(text1.isFirstResponder)
    {
        text1.text = text1.text! + sender.titleLabel!.text!
        editChanged(text1)
    }
    else if(text2.isFirstResponder)
    {
        text2.text = text2.text! + sender.titleLabel!.text!
        editChanged(text2)
    }
}

@IBAction func editChanged(_ sender: Any) {
    print("Text Changed", sender)
    // do whatever else you want to do here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM