這僅適用於整數值,我從另一個 stackoverflow 問題中發現了這一點,但是我如何設置樣式以允許小數位。我是 macOS 的新手,感謝您的幫助!
類 OnlyIntegerValueFormatter: NumberFormatter {
override func isPartialStringValid(_ partialString: String, newEditingString newString: AutoreleasingUnsafeMutablePointer<NSString?>?, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool {
// Ability to reset your field (otherwise you can't delete the content)
// You can check if the field is empty later
if partialString.isEmpty {
return true
}
// Optional: limit input length
if partialString.count > 8 {
return false
}
// Actual check
return Int(partialString) != nil
}
}
要允許十進制數,您可以將 return 語句更新為以下內容
// ...
return number(from: partialString) != nil
}
然後你允許整數和十進制數
還有更多可用選項(例如maximumIntegerDigits
)通過使用NumberFormatter
(https://developer.apple.com/documentation/foundation/numberformatter)來限制您的輸入
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句