2016-05-12 4 views
1

Ich habe zwei identische Funktionen in meinem ViewController und es scheint, dass keiner von ihnen umbenannt werden kann.Identischer TextFeldfunktionen in swift

Die erste wird verwendet, um Zeichen zu begrenzen und die Zahl links anzuzeigen.

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

     if let textField = textField as? UITextField { 

     if (range.length + range.location > textField.text!.characters.count) { 
       return false; 
     } 

     let newLength = textField.text!.characters.count + string.characters.count - range.length; 
     cLabel.text = String(25 - newLength) 
     return newLength <= 25 // To just allow up to … characters 

     } 
    return true; 
    } 

Die zweite aktiviert eine Schaltfläche, wenn Text zu demselben TextField hinzugefügt wird.

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

     // Find out what the text field will be after adding the current edit 
     let text = (ahskField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string) 

     if text.isEmpty{//Checking if the input field is not empty 
      ahskButton.userInteractionEnabled = false //Enabling the button 
      ahskButton.enabled = false 
     } else { 
      ahskButton.userInteractionEnabled = true //Disabling the button 
      ahskButton.enabled = true 
     } 

     // Return true so the text field will be changed 
     return true 
    } 

Gibt es eine Möglichkeit, sie oder irgendetwas zu kombinieren?

Antwort

0

Sie benötigen nur eine der shouldChangeCharactersInRange Funktionen.

Setzen Sie alle Ihre Logik in die eine Methode.

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

    // Find out what the text field will be after adding the current edit 
    let text = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string) 
    let newLength = text.characters.count 
    if newLength <= 25 { 
     cLabel.text = String(25 - newLength) 
     if text.isEmpty { //Checking if the input field is not empty 
      ahskButton.userInteractionEnabled = false //Enabling the button 
      ahskButton.enabled = false 
     } else { 
      ahskButton.userInteractionEnabled = true //Disabling the button 
      ahskButton.enabled = true 
     } 

     return true; 
    } else { 
     return false; 
    } 
} 
+0

funktioniert besser als zuvor, danke! – somejonus

Verwandte Themen