Ir para conteúdo
  • Cadastre-se

Formatar UITextField


Posts Recomendados

  • Respostas 5
  • Criado
  • Última resposta

Top Postadores Neste Tópico

Você pode definir o teclado desse TextField para UIKeyboardTypeDecimalPad assim:

textextField.keyboardType = UIKeyboardTypeDecimalPad;

Ou então, pode escrever um código, que à cada alteração no textfield, você verifica se é um caracter inválido. Observe o Exemplo:

- (IBAction)validateString:(id)sender {

	if ([weightTextField isFirstResponder]) {
		const char *weight = [weightTextField.text UTF8String];

		if (weight[weightTextField.text.length-1] == ',') {

			if((weightTextField.text.length-1) > 0) weightTextField.text = [weightTextField.text stringByReplacingOccurrencesOfString:@"," withString:@"."];
			else weightTextField.text = [weightTextField.text stringByReplacingOccurrencesOfString:@"," withString:@""];
		}
	}
	else if ([heightTextField isFirstResponder]) {
		const char *height = [heightTextField.text UTF8String];

		if (height[heightTextField.text.length-1] == ',') {
			if ((heightTextField.text.length-1) > 0) heightTextField.text = [heightTextField.text stringByReplacingOccurrencesOfString:@"," withString:@"."];
			else heightTextField.text = [heightTextField.text stringByReplacingOccurrencesOfString:@"," withString:@""];

		}
	}
	else if ([poundsTextField isFirstResponder]) {
		const char *pounds = [poundsTextField.text UTF8String];

		if (pounds[poundsTextField.text.length-1] == ',') {
			if ((poundsTextField.text.length-1)) poundsTextField.text = [poundsTextField.text stringByReplacingOccurrencesOfString:@"," withString:@"."];
			else poundsTextField.text = [poundsTextField.text stringByReplacingOccurrencesOfString:@"," withString:@""];
		}

	}
	else if ([feetTextField isFirstResponder]) {
		const char *feet = [feetTextField.text UTF8String];

		if (feet[feetTextField.text.length-1] == ',') {
			if ((feetTextField.text.length-1) > 0) feetTextField.text = [feetTextField.text stringByReplacingOccurrencesOfString:@"," withString:@"."];
			else feetTextField.text = [feetTextField.text stringByReplacingOccurrencesOfString:@"," withString:@""];
		}
	}

}

O código acima verifica se o usuário digitou uma vírgula e, caso tenha digitado, sustitui-a por um ponto. Além disso, você pode fazer a mesma coisa, mas em vez de substituir o caracter indesejado por um ponto, substitua por uma string vazia. desse modo:

 [textField.text stringByReplacingOccurrencesOfString:@"/* AQUI ENTRA O CARACTER INDESEJADO */" withString:@""]; 

O método acima, no interface builder, deve ser conectado ao seu TextField e a forma de chamada deve ser "EditingChanged", assim, toda vez que o user digitar algo, o seu método será chamado e os caracteres verificados.

Link para o comentário
Compartilhar em outros sites

Tem 2 pontos, Auto-formatação e Validação de Input, pelo texto do post acredito que vc queira validação de Input apesar do titulo falar em formatação ... enfim mais pro final vou por um exemplo de Auto-formatação.

No header vc declara que vai ser o delegate do text field ...

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITextFieldDelegate>
{

    UITextField *textValue;
}

@property (strong, nonatomic) IBOutlet UITextField *textValue;


@end

no arquivo .m vc adiciona

- (void)viewDidLoad
{
    textValue.delegate = self;

    [super viewDidLoad];
}

e pode usar o método do delegate abaixo ... no caso o método abaixo vai limitar a string no UITextfield a 6 caracteres ...

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    return !([newString length] > 6);
}

de resto só fazer as validações que vc necessita ... se precisar autoformatar um preço por exemplo ...


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:
(NSRange)range replacementString:(NSString *)string {
    double currentValue = [ViewController removeFormatPrice:textField.text];
    double cents = round(currentValue * 100.0f);

    if (([string isEqualToString:@"."]) && ((int)currentValue == 0)) {
        cents = floor(cents * 100);
    } else if ([string length]) {
        for (size_t i = 0; i < [string length]; i++) {
            unichar c = [string characterAtIndex:i];
            if (isnumber(c)) {
                cents *= 10;
                cents += c - '0'; 
            }            
        }
    } else {
        // back Space
        cents = floor(cents / 10);
    }

    NSString *str = [NSString stringWithFormat:@"%f", cents];
    if ([str length] > 15) {
        NSString *newStr = [str substringFromIndex:1];
        cents = [newStr doubleValue];
    }

    textField.text = [ViewController addFormatPrice:[[NSString 
                                                      stringWithFormat:@"%.2f", cents / 100.0f] doubleValue]];

    return NO;

}

+(NSString*)addFormatPrice:(double)dblPrice {   
    NSNumber *temp = [NSNumber numberWithDouble:dblPrice];
    NSDecimalNumber *someAmount = [NSDecimalNumber decimalNumberWithDecimal: [temp decimalValue]];   
    NSNumberFormatter *currencyFormatter = [[[NSNumberFormatter alloc] init] autorelease];

    //NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];  //use assim se não estiver usando o Arc do IOS5
    [currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];    
    return [currencyFormatter stringFromNumber:someAmount];
}

+(double)removeFormatPrice:(NSString *)strPrice {   
    NSNumberFormatter *currencyFormatter = [[[NSNumberFormatter alloc] init] autorelease]; 

    //NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];  //use assim se estiver usando o Arc do IOS5


    [currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    NSNumber* number = [currencyFormatter numberFromString:strPrice];
    return [number doubleValue];
}


Editado por Artur Felipe
Link para o comentário
Compartilhar em outros sites

Artur

Este codigo ficou legal

Me diz uma coisa

No meu caso tenho 2 campos na mesma tela

codigo pode ser de 1 ate 999999

e

juro pode ser 0.00 ate 999.99

se eu coloco o delegate pros 2 campos ele sempre faz a mesma ação, como eu defino dentro do delegate que pra cada campo tem uma ação diferente, como saber o nome de cada campo?

dario

Tem 2 pontos, Auto-formatação e Validação de Input, pelo texto do post acredito que vc queira validação de Input apesar do titulo falar em formatação ... enfim mais pro final vou por um exemplo de Auto-formatação.

No header vc declara que vai ser o delegate do text field ...

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITextFieldDelegate>
{

    UITextField *textValue;
}

@property (strong, nonatomic) IBOutlet UITextField *textValue;


@end

no arquivo .m vc adiciona

- (void)viewDidLoad
{
    textValue.delegate = self;

    [super viewDidLoad];
}

e pode usar o método do delegate abaixo ... no caso o método abaixo vai limitar a string no UITextfield a 6 caracteres ...

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    return !([newString length] > 6);
}

de resto só fazer as validações que vc necessita ... se precisar autoformatar um preço por exemplo ...


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:
(NSRange)range replacementString:(NSString *)string {
    double currentValue = [ViewController removeFormatPrice:textField.text];
    double cents = round(currentValue * 100.0f);

    if (([string isEqualToString:@"."]) && ((int)currentValue == 0)) {
        cents = floor(cents * 100);
    } else if ([string length]) {
        for (size_t i = 0; i < [string length]; i++) {
            unichar c = [string characterAtIndex:i];
            if (isnumber(c)) {
                cents *= 10;
                cents += c - '0'; 
            }            
        }
    } else {
        // back Space
        cents = floor(cents / 10);
    }

    NSString *str = [NSString stringWithFormat:@"%f", cents];
    if ([str length] > 15) {
        NSString *newStr = [str substringFromIndex:1];
        cents = [newStr doubleValue];
    }

    textField.text = [ViewController addFormatPrice:[[NSString 
                                                      stringWithFormat:@"%.2f", cents / 100.0f] doubleValue]];

    return NO;

}

+(NSString*)addFormatPrice:(double)dblPrice {   
    NSNumber *temp = [NSNumber numberWithDouble:dblPrice];
    NSDecimalNumber *someAmount = [NSDecimalNumber decimalNumberWithDecimal: [temp decimalValue]];   
    NSNumberFormatter *currencyFormatter = [[[NSNumberFormatter alloc] init] autorelease];

    //NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];  //use assim se não estiver usando o Arc do IOS5
    [currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];    
    return [currencyFormatter stringFromNumber:someAmount];
}

+(double)removeFormatPrice:(NSString *)strPrice {   
    NSNumberFormatter *currencyFormatter = [[[NSNumberFormatter alloc] init] autorelease]; 

    //NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];  //use assim se estiver usando o Arc do IOS5


    [currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    NSNumber* number = [currencyFormatter numberFromString:strPrice];
    return [number doubleValue];
}


Link para o comentário
Compartilhar em outros sites

se o usuário vai inserir dados em 2 ou mais uitextfield ... pra min o método mais facil é verificar qual ele está inserindo no momento seria pelo isFirstResponder ... basicamente vc procura quem está com o "foco" no momento ...

if ([textValue isFirstResponder]) {

formatação do primeiro textfield

}

else if ([textValue2 isFirstResponder]) {

formatação do segundo textfield

}

e por ai vai ...

Link para o comentário
Compartilhar em outros sites

Participe do debate

Você pode postar agora e se registrar depois. Se você tem uma conta, entre agora para postar com ela.

Visitante
Responder este tópico…

×   Você colou conteúdo com formatação.   Remover formatação

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Limpar editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Quem Está Navegando   0 membros estão online

    • Nenhum usuário registrado visualizando esta página.



  • Estatísticas do Fórum

    • Total de Tópicos
      56.8k
    • Total de Posts
      465.7k
×
×
  • Criar Novo...