2016-05-12 8 views
1

私のViewControllerには2つの同じ機能があり、どちらも名前を変更できないようです。即時の同じテキストのフィールド機能

最初の文字は、文字を制限し、残りの数字を表示するために使用されます。

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; 
    } 

2番目のボタンは、テキストが同じtextFieldに追加されたときにボタンを有効にします。

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 
    } 

これらを組み合わせる方法はありますか?

答えて

0

shouldChangeCharactersInRangeのいずれかが必要です。

すべてのロジックを1つの方法に入れます。

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

ありがとうございました! – somejonus

関連する問題