我有一個文本欄位,用戶只能輸入 6 位小數,如果有小數,如果沒有,那么他可以輸入用戶想要的任意數量的字符。
例如,我允許這個:7472828282 和這個:0,123456,而不是這個:0,2139213773219312。
并且我當前的實作對于上面的示例以及當用戶從 ekeyboard 進行輸入時是可以的,但是當用戶粘貼某些值時我無法使其作業,例如用戶可以粘貼此值:0,123456789,但我會喜歡在小數點后 6 位后截斷它,實際上是這樣的:0,123456,不,我不需要將它四舍五入到更大的小數點,我需要截斷它!
感謝您的幫助,我到目前為止的代碼如下
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField === self.amountView.textField {
guard let text = textField.text, let decimalSeparator = NSLocale.current.decimalSeparator else {
return true
}
var splitText = text.components(separatedBy: decimalSeparator)
let totalDecimalSeparators = splitText.count - 1
let isEditingEnd = (text.count - 3) < range.lowerBound
splitText.removeFirst()
if splitText.last?.count ?? 0 > 5 && string.count != 0 && isEditingEnd {
return false
}
if totalDecimalSeparators > 0 && string == decimalSeparator {
return false
}
}
return true
}
uj5u.com熱心網友回復:
此代碼始終更新內容textField但限制小數位數:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let decimalSeparator = NSLocale.current.decimalSeparator else {return true}
// Updates the text
var updatedText = (textView.text as NSString).replacingCharacters(in: range, with: text)
// If someone needs to cover all possible decimal separator values, the commented line below is the solution
// let textComponents = updatedText.components(separatedBy: [",", "."])
let textComponents = updatedText.components(separatedBy: decimalSeparator)
// Truncates the decimals
if textComponents.count > 1 && textComponents[1].count > 6{
updatedText = textComponents[0].appending(decimalSeparator).appending((textComponents[1] as NSString).substring(to: 6))
}
textView.text = updatedText
// The text has already been updated, so returns false
return false
}
uj5u.com熱心網友回復:
您的錯誤:您正在檢查舊內容。
shouldChangeCharacters 為您提供舊文本(仍在文本欄位中)、要替換的范圍(選擇或只是插入點)和替換。如果范圍被替換,您首先需要計算新文本,然后檢查該結果。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/359218.html
上一篇:按鈕影像上的中心標題
下一篇:在UIKit中顯示領域資料
