简体   繁体   中英

Swift: How to make UITextField react when its text isn't set by a user?

I have two textfields and editing one of them results in filling the other one:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

   dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {

        if textField == self.mgdlTextField {

            if let text = textField.text {
                if let value = Double(text) {
                    self.mmolTextField.text = "\(value / 38.6)"
                    return
                }
            }
            self.mmolTextField.text = ""


        } else {

            if let text = textField.text {
                if let value = Double(text) {
                    self.mgdlTextField.text = "\(value * 38.6)"
                    return
                }
            }
            self.mgdlTextField.text = ""
        }

    }

    return true
}

The problem occurs when I want to retrieve the value of the self-filled text field, I add target:

cell.mmolTextField.addTarget(self, action: "updateLDL1:", forControlEvents: UIControlEvents .EditingChanged)

The action above is not called, I suppose this might be the result of the fact that this was not noticed as a control event. I tried changing .EditingChanged into .AllEvents but this is not the solution.

How would you approach such issue? Maybe NSNotifications may come in handy?

Thanks in advance

您需要自己触发事件:

self.mmolTextField.sendActionsForControlEvents(.EditingChanged)

I believe you assigned a delegate to your UITextField. The delegate has methods textFieldDidBeginEditing: and textFieldDidEndEditing: that should help you here. No need to implement other touch controls.

You can use Key Value coding:

var textField: UITextField!
var observer: NSObject!

func textFieldObserverTest() {
    if textField == nil {
        textField = UITextField()
        observer = TextFieldObserver()
        textField.addObserver(observer, forKeyPath: "text", options: NSKeyValueObservingOptions.New, context: nil)
    }
    textField.text = "Hello World"
    textField.text = "Goodbye World"
    textField.text = "Its all over"
}

class TextFieldObserver : NSObject {
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    print("\(keyPath!) changed to \(change![NSKeyValueChangeNewKey])")
}

}

Try using UIControlEventValueChanged

this is for Obj-C find equivalent for swift.

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