简体   繁体   中英

Swift Xcode 6: How do I use multiple functions in one statement?

I am a newcomer in xcode and swift, and I am having a problem with using two IBActions to allow a button to be enabled. I have 2 text fields, and I have a button that is disabled. I want the button to be enabled when both of the text fields are filled in. How can I do this? So far I have declared two functions with IBActions for the two text fields:

 @IBAction func yourWeightEditingDidBegin(sender: AnyObject) {

}

@IBAction func calorieNumberEditingDidBegin(sender: AnyObject) {

}

Thanks!

One way is to use the UITextFieldDelegate function instead of IBOutlets:

func textFieldShouldReturn(textField: UITextField!) -> Bool {

    textField.resignFirstResponder()

    if yourWeight.text != ""  && calorieNumber.text != "" {

        button.enabled = true
    }

    return true
}

I, too, implement UITextFieldDelegate , but I use shouldChangeCharactersInRange . This way, the status of that button changes as the user types:

If dealing with only two text fields, it looks like:

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

    // get the value this text field will have after the string is replaced

    let value: NSString = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string)

    // get the value of the other text field

    let otherValue = textField == yourWeight ? calorieNumber.text : yourWeight.text

    // only enable done if these are both non-zero length

    doneButton.enabled = (value != "" && otherValue != "")

    return true
}

Clearly, for this to work, you must specify the delegate for both of those text fields (either in IB or programmatically). I also generally marry the above with the "auto-enable return key" option for the text fields, too.

You don't. Instead, try something like this

var weightIsFilled = false
var calorieNumberIsFilled = false

@IBAction func yourWeightEditingDidBegin(sender: AnyObject) {
 if valueOfWeightTextFieldIsValid() {
   self.weightIsFilled = true
 }
 if self.weightIsFilled && self.calorieNumberIsFilled {
   self.enableButton()
 }
}

@IBAction func calorieNumberEditingDidBegin(sender: AnyObject) {
 if valueOfCalorieNumberTextFieldIsValid() {
   self.calorieNumberIsFilled = true
 }
 if self.weightIsFilled && self.calorieNumberIsFilled {
   self.enableButton()
 }
}

You also may want to be using IBAction functions that are called when the textfield's value changes, not when editing begins on it.

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