2017-05-26 93 views
1

迅速兩種不同的文本框限制的文本字符第二個文本字段,他們可以鍵入20個字符,只是不知道如何把它放到一個shouldchangecharacter func作爲即時通訊猜測你不做兩個單獨的函數,因爲這不適合我?迅速 - 在同一個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 

} 

//文本字段2

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 

} 

只需將您的兩個文本字段名稱替換爲您的網點即可:)