Formatting a UITextField for credit card input like (xxxx xxxx xxxx xxxx)

前端 未结 28 2091
长情又很酷
长情又很酷 2020-11-28 01:19

I want to format a UITextField for entering a credit card number into such that it only allows digits to be entered and automatically inserts spaces so that the

28条回答
  •  独厮守ぢ
    2020-11-28 01:47

    i modified @ilesh answer so it only shows the last 4 digits no matter what the lenght is. Also to ignore the space and "-" chars. This way, if we have a number with the format 0000 - 0000 - 0000 - 0000 it displays XXXX - XXXX - XXXX - 0000

    func setStringAsCardNumberWithSartNumber(Number:Int,withString str:String) -> String{
        let arr = str.characters
        var CrediteCard : String = ""
        let len = str.characters.count-4
        if arr.count > (Number + len) {
            for (index, element ) in arr.enumerated(){
                if index >= Number && index < (Number + len) && element != "-" && element != " " {
                    CrediteCard = CrediteCard + String("X")
                }else{
                    CrediteCard = CrediteCard + String(element)
                }
            }
            return CrediteCard
        }else{
            print("\(Number) plus \(len) are grether than strings chatarter \(arr.count)")
        }
        print("\(CrediteCard)")
        return str
    }
    

提交回复
热议问题