UITextFieldがあり、クリックすると左下に小数点付きのテンキーが表示されます。ユーザーが小数点を1つしか配置できないようにフィールドを制限しようとしています
例:
2.5 OK
2..5 NOT OK
UITextFieldがあり、クリックすると左下に小数点付きのテンキーが表示されます。ユーザーが小数点を1つしか配置できないようにフィールドを制限しようとしています
例:
2.5 OK
2..5 NOT OK
次のように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つの要素が含まれます。
これは正規表現を使用した例です。この例では、小数点以下1桁と小数点以下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;
}
Swift 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)。
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Allow to remove character (Backspace)
if string == "" {
return true
}
// Block multiple dot
if (textField.text?.contains("."))! && string == "." {
return false
}
// Check here decimal places
if (textField.text?.contains("."))! {
let limitDecimalPlace = 2
let decimalPlace = textField.text?.components(separatedBy: ".").last
if (decimalPlace?.count)! < limitDecimalPlace {
return true
}
else {
return false
}
}
return true
}
//Create this variable in .h file or .m file
float _numberOfDecimal;
//assign value in viewDidLoad method
numberOfDecimal = 2;
#pragma mark - TextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// Allow to remove character (Backspace)
if ([string isEqualToString:@""]) {
return true;
}
// Block multiple dot
if ([textField.text containsString:@"."] && [string isEqualToString:@"."]) {
return false;
}
// Check here decimal places
if ([textField.text containsString:@"."]) {
NSString *strDecimalPlace = [[textField.text componentsSeparatedByString:@"."] lastObject];
if (strDecimalPlace.length < _numberOfDecimal) {
return true;
}
else {
return false;
}
}
return true;
}
Swift 2.3の場合、ユーザーが2桁の後に10進数を入力できないようにします-
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
}
}
}
}
受け入れられた答えに基づいて、次のアプローチは、お金の形式を扱うときに役立つ3つのケースを検証します。
テキストフィールドのデリゲートが適切に設定されていること、クラスが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;
}
-(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];
}
}
}
}
これを試して :-
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
}
スウィフト3
配列を作成してカウントを確認する必要はありません。制限ユーザーは、このように小数点を1つしか配置できません。
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if (textField.text?.contains("."))! && string.contains(".")
{
return false
}
else
{
return true
}
}
スウィフト4
整数の最大数数値は4、つまり9999であり、小数点以下の最大桁数の制限は2です。したがって、最大数は9999.99になります。
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// 100 is the tag value of our textfield
/*or you may use "if textfield == myTextField{" if you have an IBOutlet to that textfield */
if textField.tag == 100 {
//max length limit of text is 8
if textField.text!.count > 8 && string != "" {
return false
}
let maxLength = 8
let currentString: NSString = textField.text! as NSString
//次のコードを使用するそのテキストフィールドに価格を入力していて、ユーザーがそのテキストフィールドに入力を開始したときに開始時に$が自動的に挿入されるようにする場合、または$の代わりに他の文字を開始に配置する場合があります。それ以外の場合は、次の3行のif条件コードにコメントします。
if currentString.length == 0 {
priceTextField.text = "$"
}
//新しく入力された文字を挿入した後の新しい文字列
let newString: NSString =
currentString.replacingCharacters(in: range, with: string) as NSString
if newString.length > maxLength{
return false
}
if (textField.text!.range(of: ".") != nil) {
let numStr = newString.components(separatedBy: ".")
if numStr.count>1{
let decStr = numStr[1]
if decStr.length > 2{
return false
}
}
}
var priceStr: String = newString as String
if (textField.text!.range(of: "$") != nil) {
priceStr = priceStr.replacingOccurrences(of: "$", with: "")
}
let price: Double = Double(priceStr) ?? 0
if price > 9999.99{
return false
}
switch string {
case "0","1","2","3","4","5","6","7","8","9":
return true
case ".":
let array = Array(textField.text!)
var decimalCount = 0
for character in array {
if character == "." {
decimalCount = decimalCount + 1
}
}
if decimalCount == 1 {
return false
} else {
return true
}
default:
let array = Array(string)
if array.count == 0 {
return true
}
return false
}
}
return true
}
UITextFieldのデリゲートを設定するオブジェクトに、「[- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string]
」に応答するメソッドを追加します。
次に、オブジェクトを使用するか、NSNumberFormatter
既存の小数点マークをブルートフォースチェックすることができます(NO
小数点がすでに存在する場合は戻ります)。
簡単に言うと、数値の形式は次のとおりです[NSString stringWithFormat:@"%9.5f", x];
。ここで、5は「、」の後の小数です。
私は、小数点以下の桁数を制御できるソリューションを作成しました。これにより、ユーザーは小数点以下1桁のみを入力でき、小数点以下の桁数も制御できます。
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;
}
スウィフト4
UITextFieldで複数の小数点(。または、)を回避するための効率的で簡単な方法:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if(string == "," || string == "." ){
if ((textField.text?.contains(","))! || (textField.text?.contains("."))!){
return false
}
}
return true
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if([string isEqualToString:@"."]) {
BOOL containsDecimal = [textField.text containsString:@"."];
return !containsDecimal;
}
return YES;
}
テキストフィールドテキストにすでに「。」が含まれている場合 次にNOを返し、それ以外の場合はYESを返します。
改善
情報:許可しない:
1:キーボードタイプを:DecimalPadに設定します
2:過去にコピー
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//!\ set the keyboard type to : Decimal Pad /!\\
// CUSTOM SETUP
let c = NSLocale.current.decimalSeparator ?? "."
let limitBeforeSeparator = 2
let limitAfterSeparator = 2
// ---------
var validatorUserInput:Bool = false
let text = (textField.text ?? "") as NSString
let newText = text.replacingCharacters(in: range, with: string)
// Validator
let pattern = "(?!0[0-9])\\d*(?!\\\(c))^[0-9]{0,\(limitBeforeSeparator)}((\\\(c))[0-9]{0,\(limitAfterSeparator)})?$"
if let regex = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive) {
validatorUserInput = regex.numberOfMatches(in: newText, options: .reportProgress, range: NSRange(location: 0, length: (newText as NSString).length)) > 0
}
if validatorUserInput {
// setting data or something eles before the return
if let char = string.cString(using: String.Encoding.utf8) {
let isBackSpace = strcmp(char, "\\b")
if (isBackSpace == -92 && textField.text?.count == 1) {
print("Backspace was pressed")
print(newText)
// do something...
} else {
print("Number Added")
print(newText)
// do something...
}
}
return validatorUserInput
} else {
return validatorUserInput
}
}
3:セパレータの前後の最大桁数xが必要な場合は、メソッドで設定します
let limitBeforeSeparator = 2
let limitAfterSeparator = 2