[英]Add a character for every 3 characters for UITextField
我正在嘗試在用戶每三個字符鍵入一次時添加一個字符,例如用戶類型: 123456789
它應該自動更改為123,456,789
。 如何在中添加字符
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
這是一種方法:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
var proposedString = (textField.text as NSString?)!.replacingCharacters(in: range, with: string)
// do whatever modifications you need to do, e.g. remove commas:
proposedString = proposedString.replacingOccurrences(of: ",", with: "")
let modulo = proposedString.count % 3
for index in stride(from: modulo, to: proposedString.count, by: 3).reversed() {
print(index)
if index != 0 {
proposedString.insert(",", at: proposedString.index(proposedString.startIndex, offsetBy: index))
}
}
// manually set the new value
textField.text = proposedString
// don't let it update itself
return false
}
注意:我的這個小算法僅適用於逗號-因此,如果逗號是您在國家/地區中顯示數字的一部分,則應該使用Locale
( docs )或NumberFormatter
( docs )添加逗號。
您應考慮到世界各地的不同地區使用不同的數字格式化方式。 為了解決這個問題,讓iOS為您進行格式化。
事實證明這非常簡單。 您需要的一行代碼是:
NumberFormatter.localizedString(from: 123456 as NSNumber, number: NumberFormatter.Style.decimal)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.