我有一個UITextField,點擊時在左下角出現一個帶有小數點的數字鍵盤。我正在嘗試限制該字段,以便用戶只能放置1個小數點。例如,
2.5 OK
2..5 NOT OK如何限制UITextField中的小數點數?
回答
貫徹shouldChangeCharactersInRange方法是這樣的:
// Only allow one decimal point
// Example assumes ARC - Implement proper memory management if not using.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSArray *arrayOfString = [newString componentsSeparatedByString:@"."];
if ([arrayOfString count] > 2)
return NO;
return YES;
}
這產生由小數點分割字符串數組,所以如果有一個以上的小數點我們將有陣列中的至少3個元素。
在任何物體您設置的UITextField的委託,添加解答了"[- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string]
"的方法。
然後,您可以使用NSNumberFormatter
對象,也可以蠻力檢查已存在的小數位標記(如果小數標記已存在,則返回NO
)。
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(textField == min_textfield)
{
if([textField.text rangeOfString:@"."].location == NSNotFound)
{
if([string isEqualToString:@"."])
{
flag_for_text = 1;
}
else
{
textField.text = [NSMutableString stringWithFormat:@"%@",textField.text];
}
}
else
{
if([string isEqualToString:@"."])
{
return NO;
}
else
{
textField.text = [NSMutableString stringWithFormat:@"%@",textField.text];
}
}
}
}
簡而言之,數字格式如下[NSString stringWithFormat:@"%9.5f", x];
其中5是「,」後面的小數。
下面是一個正則表達式的例子,該例子僅限於一個小數點和2個小數點。您可以調整它以適應您的需求。
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSString *expression = @"^[0-9]*((\\.|,)[0-9]{0,2})?$";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression options:NSRegularExpressionCaseInsensitive error:&error];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString options:0 range:NSMakeRange(0, [newString length])];
return numberOfMatches != 0;
}
好的答案。作爲一個建設性的評論家,我會建議您提高RegEx知識。比如「([0-9] +)?」可以替換爲「[0-9] *」,這使得它更具可讀性,並且性能更高。我已經對答案做了適當的改進。 –
@「^ - ?[0-9] *((\\。|,)[0-9] {0,2})?$」也可以輸入負數。 –
大廈接受的答案,下面的方法確認3例錢格式處理時很有用:
- 極大量小數點後
- 超過200個字符
- 超過1小數點
請確保您的文本字段的del egate設置正確,你的類符合UITextField
協議,並添加下面的委託方法。
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// Check for deletion of the $ sign
if (range.location == 0 && [textField.text hasPrefix:@"$"])
return NO;
NSString *updatedText = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSArray *stringsArray = [updatedText componentsSeparatedByString:@"."];
// Check for an absurdly large amount
if (stringsArray.count > 0)
{
NSString *dollarAmount = stringsArray[0];
if (dollarAmount.length > 6)
return NO;
}
// Check for more than 2 chars after the decimal point
if (stringsArray.count > 1)
{
NSString *centAmount = stringsArray[1];
if (centAmount.length > 2)
return NO;
}
// Check for a second decimal point
if (stringsArray.count > 2)
return NO;
return YES;
}
有一種情況沒有正確處理:如果您在dollarAmount中已達到6個字符,則無論如何您都可能想要輸入centAmount。 –
我做出瞭解決方案,爲您帶來控制小數計算,所以用戶可以鍵入只有一個小數點分隔符,你也可以有超過小數的控制數。
只需設置decimalPlacesLimit正確的值。
查看方法:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSLog(@"text on the way: %@", string);
NSUInteger decimalPlacesLimit = 2;
NSRange rangeDot = [textField.text rangeOfString:@"." options:NSCaseInsensitiveSearch];
NSRange rangeComma = [textField.text rangeOfString:@"," options:NSCaseInsensitiveSearch];
if (rangeDot.length > 0 || rangeComma.length > 0){
if([string isEqualToString:@"."]) {
NSLog(@"textField already contains a separator");
return NO;
} else {
NSArray *explodedString = [textField.text componentsSeparatedByString:@"."];
NSString *decimalPart = explodedString[1];
if (decimalPart.length >= decimalPlacesLimit && ![string isEqualToString:@""]) {
NSLog(@"textField already contains %d decimal places", decimalPlacesLimit);
return NO;
}
}
}
return YES;
}
試試這個: -
public func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
if(text == "," || text == "."){
let countdots = textView.text!.componentsSeparatedByString(".").count - 1
if countdots > 0 && (text == "." || text == ",")
{
return false
}
}
return true
}
'text'可以是多個字符,所以你不能像這樣檢查它。 – trapper
爲SWIFT 2。3,防止用戶對後兩個地方輸入十進制數 -
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
let decimalPlacesLimit = 2
let rangeDot = txtPrice.text!.rangeOfString(".", options: .CaseInsensitiveSearch)
if rangeDot?.count > 0
{
if (string == ".")
{
print("textField already contains a separator")
return false
}
else {
var explodedString = txtPrice.text!.componentsSeparatedByString(".")
let decimalPart = explodedString[1]
if decimalPart.characters.count >= decimalPlacesLimit && !(string == "")
{
print("textField already contains \(decimalPlacesLimit) decimal places")
return false
}
}
}
}
歡迎來到Stack Overflow!儘管您可能已經解決了此用戶的問題,但僅有代碼的答案對於未來出現此問題的用戶來說並不是很有幫助。請編輯您的答案,以解釋爲什麼您的代碼可以解決原始問題。 –
斯威夫特3
無需創建一個數組,並檢查計數。限制用戶只能像這樣放置1個小數點。
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if (textField.text?.contains("."))! && string.contains(".")
{
return false
}
else
{
return true
}
}
夫特3實現此UITextFieldDelegate方法,以防止用戶從輸入的數字無效:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let text = (textField.text ?? "") as NSString
let newText = text.replacingCharacters(in: range, with: string)
if let regex = try? NSRegularExpression(pattern: "^[0-9]*((\\.|,)[0-9]*)?$", options: .caseInsensitive) {
return regex.numberOfMatches(in: newText, options: .reportProgress, range: NSRange(location: 0, length: (newText as NSString).length)) > 0
}
return false
}
它正與兩個逗號或點爲十進制分隔符。您還可以使用此模式限制小數位數:"^[0-9]*((\\.|,)[0-9]{0,2})?$"
(在本例中爲2)。
- 1. 限制UITextField中小數點前後的位數
- 2. 如何限制UItextfield
- 3. Swift:如何限制浮點數的小數點?
- 4. 如何在python隨機數限制小數點後的位數
- 5. 限制小數點後的位數
- 6. Swift中的UITextfield字符數限制
- 7. 如何限制小數?
- 8. 如何製作帶限制的UITextField
- 9. 限制小數點到所需要的
- 10. 限制小數
- 11. 限制輸入到UITextField的字符數
- 12. 如何將html輸入限制爲正數小數點後兩位小數?
- 13. 如何在字符串中限制小數點,在python
- 14. 用戶設置的函數中的可變小數點限制?
- 15. 限制UITextField中的條目
- 16. iphone中的UITextfield chacter限制
- 17. 限制使用小數點前的整數數字。數字
- 18. Asp.net如何限制textbox keypress事件中小數點前後的位數
- 19. 在Perl中,如何限制小數點後的位數,但沒有尾隨零?
- 20. 的UITextField限制,iphone
- 21. 限制到一個小數點
- 22. 限制雙到小數點後兩位
- 23. 限制爲單個小數點
- 24. UITextField - 限制文本長度不受字符數的限制
- 25. 限制標籤中小數點後的位數
- 26. javascript中小數點後的數字限制
- 27. 限制DBGrid中的小數位數
- 28. 如何在UITextField中的小數點後防止超過2個數字?
- 29. 限制小數位數
- 30. 如何限制JavaScript輸出中的小數位數?
而不是使用componentsSeparatedByString,您可以使用NSRegularExpression來確定newString是否包含多個小數。 –
真的!有很多方法可以做到這一點。我通常使用這個,因爲我經常想要做一些不同的整數和小數部分。 – lnafziger
使用正則表達式可以更好地控制文本字段接受的字符以及它們將採用的格式。 – nizx