简体   繁体   中英

Swift text field combine two functions

Hi I have a following code for my text field function which only allows numbers, dot and no more then 7 characters total:

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

    let length = ((textField.text?.characters.count)! + string.characters.count)
    if (length > 7)
    {
        return false
    }
    else
    {
     //   return true
        let inverseSet = NSCharacterSet(charactersIn:".0123456789").inverted
        let components = string.components(separatedBy: inverseSet)
        let filtered = components.joined(separator: "")
        return string == filtered && true
    }
    }

Now I found another good piece of code on this site which only allows one decimal character:

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


    if(string == "." ){
        let countdots = textField.text!.components(separatedBy: ".").count - 1

        if countdots > 0 && string == "."
        {
            return false
        }
    }
    return true

}

I'm trying to wrap my head around how to combine these things into one function ? Keep getting errors.. Maybe somebody can suggest?

They can be combined using basic control flow (else if).

As an aside, the line return string == filtered && true is poorly written. If string == filtered it will return true and if string != filtered it will return false. Hence, the && clause is a useless addition. Rewrite it as return string == filtered .

With this in mind, here is your function cleaned up:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let length = ((textField.text?.characters.count)! + string.characters.count)
    if (length > 7) {
        return false
    }
    else if(string == "." ) {
        let countdots = textField.text!.components(separatedBy: ".").count - 1
        if countdots > 0 && string == "." {
        return false
        }
        return true
    }
    else
    {
     // return true if the string is equivalent after removing all non-numbers (and therefore consisted of only numbers)
        let inverseSet = NSCharacterSet(charactersIn:".0123456789").inverted
        let components = string.components(separatedBy: inverseSet)
        let filtered = components.joined(separator: "")
        return string == filtered
    }
}

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