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

前端 未结 28 2176
长情又很酷
长情又很酷 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:55

    These answers are all just way too much code for me. Here's a solution in Swift 2.2.1

    extension UITextField {
    
        func setText(to newText: String, preservingCursor: Bool) {
            if preservingCursor {
                let cursorPosition = offsetFromPosition(beginningOfDocument, toPosition: selectedTextRange!.start) + newText.characters.count - (text?.characters.count ?? 0)
                text = newText
                if let newPosition = positionFromPosition(beginningOfDocument, offset: cursorPosition) {
                    selectedTextRange = textRangeFromPosition(newPosition, toPosition: newPosition)
                }
            }
            else {
                text = newText
            }
        }
    }
    

    Now just put an IBAction in your view controller:

    @IBAction func textFieldEditingChanged(sender: UITextField) {
        var digits = current.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet).joinWithSeparator("") // remove non-digits
        // add spaces as necessary or otherwise format your digits.
        // for example for a phone number or zip code or whatever
        // then just:
        sender.setText(to: digits, preservingCursor: true)
    }
    

提交回复
热议问题