我有一個textfield
,最大字符範圍爲16,我想在每4個字符後加上減號字符或空格,然後寫入其他字符,例如5022-2222- 2222-2222。 有我的代碼,但這是行不通的,怎麼能做到這一點?在輸入文本字段時在文本字符之間添加空格
if textField.text?.characters.count == 5 {
let l = textField.text?.characters.count
let attributedString = NSMutableAttributedString(string: cartNumberTextField.text!)
attributedString.addAttribute(NSKernAttributeName, value: CGFloat(4.0), range: NSRange(location: l!, length: 4))
cartNumberTextField.attributedText = attributedString
}
else if textField.text?.characters.count == 9 {
let l = textField.text?.characters.count
let attributedString = NSMutableAttributedString(string: cartNumberTextField.text!)
attributedString.addAttribute(NSKernAttributeName, value: CGFloat(4.0), range: NSRange(location: l!, length: 4))
cartNumberTextField.attributedText = attributedString
}
else if textField.text?.characters.count == 13 {
let l = textField.text?.characters.count
let attributedString = NSMutableAttributedString(string: cartNumberTextField.text!)
attributedString.addAttribute(NSKernAttributeName, value: CGFloat(4.0), range: NSRange(location: l!, length: 4))
cartNumberTextField.attributedText = attributedString
}
我在UITextField
shouldChangeCharactersIn
範圍的方法,添加以下代碼。