2017-05-26 7 views
1

迅速に2つの異なるテキストフィールドの制限のテキスト文字2番目のテキストフィールドは20文字で入力することができ、これを1文字に入れる方法がわからないのは私にとってはうまく機能しないため、2つの別々の関数を実行しないと思いますか? //テキストフィールド迅速 - 同じVC

//テキストフィールド1

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

    let currentCharacterCount = textfield1.text?.characters.count ?? 0 

if (range.length + range.location > currentCharacterCount){ 
    return false 

} 
let newLength = currentCharacterCount + string.characters.count - range.length 


return newLength <= 10 

} 
func textField2(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { 

    let currentCharacterCount2 = TextField2.text?.characters.count ?? 0 

    if (range.length + range.location > currentCharacterCount2){ 
     return false 

    } 
    let newLength = currentCharacterCount2 + string.characters.count - range.length 


    return newLength <= 20 

} 

答えて

1

あなたのビュー内の両方のテキストフィールドに店舗を持っている場合は、このような何かを行うことができます。

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

    let currentCharacterCount = textField.text?.characters.count ?? 0 

    if (range.length + range.location > currentCharacterCount){ 
     return false 

    } 
    let newLength = currentCharacterCount + string.characters.count - range.length 

    var maxLength = 0 
    if textField.isEqual(textField1) { 
     maxLength = 10 
    } else if textField.isEqual(textField2) { 
     maxLength = 20 
    } 

    return newLength <= maxLength 

} 

2つのテキストフィールド名をコンセントの名前に置き換えてください:)