In My app I have a UITextField. When a user enters text such as 123456 it should appear something like 123,456.00 in the textfield.
The following code is used:
UITextField *txt = [[UITextField alloc]initWithFrame:CGRectMake(300, 120+y*58, 280, 31)];
txt.keyboardType = UIKeyboardTypeDecimalPad;
txt.borderStyle = UITextBorderStyleRoundedRect;
txt.font = [UIFont systemFontOfSize:15];
txt.textAlignment = NSTextAlignmentLeft;
txt.returnKeyType = UIReturnKeyDefault;
txt.delegate = self;
[txt addTarget:self action:#selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
-(void)textFieldDidChange:(UITextField *)theTextField
{
NSString *textFieldText = [theTextField.text stringByReplacingOccurrencesOfString:#"," withString:#""];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *number = [formatter numberFromString:textFieldText];
NSString *formattedOutput = [formatter stringFromNumber:number];
theTextField.text=formattedOutput;
}
Use below code
NSString *textFieldText = theTextField.text ;
float f = [theString floatValue];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMinimumFractionDigits:2];
[formatter setMaximumFractionDigits:2];
[formatter setLocale:[NSLocale currentLocale]];
NSLog(#"%#", [formatter stringFromNumber:#(f)]);
Set MinimumFractionDigits to 2 & MaximumFractionDigits to 2.Try above code in textFieldDidEndEditing delegate method of textfield.
You are almost close to your solution just few things need enhancement. First you must have to specify the maximum and minimum allowed fractions digits like this:
[formatter setMinimumFractionDigits:2];
[formatter setMaximumFractionDigits:2];
It will fix the *.00 problem, then there is another problem of updating it back to the UI. Since you are setting the textfield text:
theTextField.text=formattedOutput;
It will lose the current position of editing and hence you will lose the ground. e.g.,
You typed 1, the above code will update the textfield with 1.00 and the cursor will move to position 5:
1.00
^^^^^
If you will edit further you won't get the expected result (the text will try to append at the end).
To fix this either you should update the text field when you finish editing using the handler textFieldDidEndEditing or you should use some other control like UILabel to display the formatted result.
Sample Code: (for demo)
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UITextField *txt = [[UITextField alloc]initWithFrame:CGRectMake(20, 120+(3)*58, 280, 31)];
txt.keyboardType = UIKeyboardTypeDecimalPad;
txt.borderStyle = UITextBorderStyleRoundedRect;
txt.font = [UIFont systemFontOfSize:15];
txt.textAlignment = NSTextAlignmentLeft;
txt.returnKeyType = UIReturnKeyDefault;
txt.delegate = self;
[self.view addSubview:txt];
[txt addTarget:self action:#selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
lbl = [[UILabel alloc] initWithFrame:CGRectMake(20, 160+(3)*58, 280, 31)];
[self.view addSubview:lbl];
}
-(void)textFieldDidChange:(UITextField *)theTextField
{
NSString *textFieldText = [theTextField.text stringByReplacingOccurrencesOfString:#"," withString:#""];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMinimumFractionDigits:2];
[formatter setMaximumFractionDigits:2];
NSNumber *number = [formatter numberFromString:textFieldText];
NSString *formattedOutput = [formatter stringFromNumber:number];
[lbl setText:formattedOutput];
}
You can set text like this to your textview.
theTextField.text = [NSString stringWithFormat:#"%.02f", floatVal];
Hope this helps.
If you add these two lines to the code snippet you posted:
[formatter setMinimumFractionDigits:2];
[formatter setMaximumFractionDigits:2];
right after the line in which you set the number formatter's style to NSNumberFormatterDecimalStyle, it should give you exactly what you want.
#"123456" would result in #"123,456.00"
and #"1" would result in #"1.00"
Related
I am working on a chat application where i am using alex barinov's chat bubble example. I am able to send/receive messages. I want to add some labels and views on each chat bubble like time, date, delivered image, etc.
I tried to add some labels over the chat bubble's contentView in UIBubbleTableViewCell.m class in method named -(void)setupInternalData, but the label (date label) gets repeated for every bubble , and it overwrites the previous label, and it contains both the labels.
Here is the address from where i downloaded the project -https://github.com/AlexBarinov/UIBubbleTableView
Below is my code for adding labels to chat bubble view -
-(void)setupInternalData{
_fromLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.frame.origin.x, self.frame.size.height-28, 100, 14)];
_fromLabel.numberOfLines = 1;
_fromLabel.baselineAdjustment = UIBaselineAdjustmentAlignBaselines;
_fromLabel.clipsToBounds = YES;
_fromLabel.layer.cornerRadius=5;
[_fromLabel setFont:[UIFont systemFontOfSize:5]];
[self.customView addSubview:_fromLabel];
//display msg sent time
NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *currentTime = [dateFormatter stringFromDate:today];
_lblMsgTime.text=currentTime;
_lblMsgTime.frame=CGRectMake(12,0, 85, 14);
_lblMsgTime.text=[NSString stringWithFormat:#"%#",currentTime];
_lblMsgTime.textAlignment = NSTextAlignmentRight;
_lblMsgTime.textColor = [UIColor blackColor];
[_fromLabel addSubview:_lblMsgTime];
[_lblMsgTime setAdjustsFontSizeToFitWidth:YES];
//date formater
NSDate *date = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"d.M.yyyy";
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateStyle:NSDateFormatterMediumStyle];
NSString *string = [formatter stringFromDate:date];
_lblMsgdate.text=string;
_lblMsgdate.frame=CGRectMake(60 ,0, 85, 14);
_lblMsgdate.text=[NSString stringWithFormat:#"%#",string];
_lblMsgdate.textAlignment = NSTextAlignmentRight;
_lblMsgdate.textColor = [UIColor blackColor];
[_fromLabel addSubview:_lblMsgdate];
[_lblMsgdate setAdjustsFontSizeToFitWidth:YES];
UIImageView *backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"ic__typ__txt.png"]];
backgroundView.frame=CGRectMake(self.frame.origin.x+1, self.frame.size.height-24, 10, 10);
[self.customView addSubview:backgroundView];
[self.customView bringSubviewToFront:_fromLabel];
[self.customView bringSubviewToFront:backgroundView];
[self.contentView addSubview:self.customView];
}
Can anyone please tell me what wrong am i doing here, and what should i be doing. Any help is appreciated. Waiting for your valuable answers.
hey i think you have to create a view and pass it.
create a view in NSBubbleData file's
- (id)initWithText:(NSString *)text date:(NSDate *)date type:(NSBubbleType)type
{
UIFont *font = [UIFont systemFontOfSize:[UIFont systemFontSize]];
CGSize size = [(text ? text : #"") sizeWithFont:font constrainedToSize:CGSizeMake(220, 9999) lineBreakMode:NSLineBreakByWordWrapping];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)];
label.numberOfLines = 0;
label.lineBreakMode = NSLineBreakByWordWrapping;
label.text = (text ? text : #"");
label.font = font;
label.backgroundColor = [UIColor clearColor];
#if !__has_feature(objc_arc)
[label autorelease];
#endif
UIEdgeInsets insets = (type == BubbleTypeMine ? textInsetsMine : textInsetsSomeone);
return [self initWithView:label date:date type:type insets:insets];
}
in this you have to create a view, in this view add uilable,uiimage which you want replace UILabel *label with custom view.
After Clicked...Date is not shown in textfield.
Textfield is in custom cell of tableview.
UIDatePicker *datePicker = [[UIDatePicker alloc]init];
[datePicker setDate:[NSDate date]];
datePicker.datePickerMode = UIDatePickerModeDate;
[datePicker addTarget:self action:#selector(dateTextField:) forControlEvents:UIControlEventValueChanged];
[txtField_date setInputView:datePicker];
-(void) dateTextField:(id)sender
{
UIDatePicker *picker = (UIDatePicker*)txtField_date.inputView;
[picker setMaximumDate:[NSDate date]];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSDate *eventDate = picker.date;
[dateFormat setDateFormat:#"dd/MM/yyyy"];
NSString *dateString = [dateFormat stringFromDate:eventDate];
txtField_date.text = [NSString stringWithFormat:#"%#",dateString];
}
Try this code.
You can use the date property on UIDatePicker and convert it to NSString and set it to your UITextField.
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy"]; // set your own format
NSString *formattedDateString = [formatter stringFromDate:yourPicker.date];
textField.text = formattedDateString;
I have a UITextField in which the user enters an amount of money. I am trying to make the textField show the current money symbol, as the user types in an amount.
So far I was able to do that in textFieldDIdEndEditing:, how can I do the following code in a method that lets you change as the user types. (For example shouldChangeTextInRange:.) This way the currency will always show, not only when the user is finished entering the amount.
Here is what I have so far:
- (void)textFieldDidEndEditing:(UITextField *)textField {
NSNumberFormatter *currencyFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[currencyFormatter setLocale:[NSLocale currentLocale]];
[currencyFormatter setMaximumFractionDigits:2];
[currencyFormatter setMinimumFractionDigits:2];
[currencyFormatter setAlwaysShowsDecimalSeparator:YES];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSNumber *someAmount = [NSNumber numberWithDouble:[textField.text doubleValue]];
NSString *string = [currencyFormatter stringFromNumber:someAmount];
textField.text = string;
}
The reason why I don't just insert it in a UILabel is because some places have their currency after the amount. (Ex. France)
Create a UIImageView with currency image.
And then set leftView either RightView of UITextField as per your requirement.
UIImage *cImage = [UIImage imageNamed:#"currency.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:cImage];
[imageView setFrame:CGRectMake(0, 0, 40, 40)];
// For Left
[textfield setLeftView:imageView];
// or
// For Right
[textfield setRightView:imageView];
Try this.
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
if (textField == txtAmount) {
if ([txtAmount.text isEqualToString:#""]) {
txtAmount.text = #"$";
}else{
txtAmount.text = [NSString stringWithFormat:#"%#",txtAmount.text];
}
}
return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
if (textField == txtAmount) {
if ([txtAmount.text isEqualToString:#"$"]) {
txtAmount.placeholder = #"Amount";
}
}
return YES;
}
and don't forget to give delegate to the UITextField.
I have two problems at UIDatePicker as inputView.
1: When I select "April 17 9 00 PM" in datePicker,
dateTextField outputs "2014-04-107 21:00:00".
2: UTC of My country is +0900.
But, NSLog outputs "2014-04-17 12:00:00 +0000".
How do I fix these problems?
#property IBOutlet UITextField* dateTextField;
#property IBOutlet UIDatePicker* datePicker;
#property UIToolbar* toolBar;
- (void)viewDidLoad
{
self.datePicker = [[UIDatePicker alloc]initWithFrame:CGRectMake(0, 600, 320, 216)];
[self.view addSubview:self.datePicker];
self.toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, -40, 320, 40)];
self.toolBar.barStyle = UIBarStyleBlackOpaque;
UIBarButtonItem* doneButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(dateTextFieldShouldReturn)];
NSArray* finishBarItems = [NSArray arrayWithObjects:doneButton, nil];
[self.toolBar setItems:finishBarItems animated:YES];
self.dateTextField = [[UITextField alloc]initWithFrame:CGRectMake(40, 293, 250, 30)];
self.dateTextField.delegate = self;
self.dateTextField.inputView = self.datePicker;
self.dateTextField.inputAccessoryView = self.toolBar;
[myScrollView addSubview:self.dateTextField];
}
- (void)dateTextFieldShouldReturn
{
NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:#"yyyy-MM-DD HH:mm:ss"];
NSString* dateString = [formatter stringFromDate:self.datePicker.date];
[self.dateTextField setText:dateString];
[self.dateTextField resignFirstResponder];
NSDate* date = [formatter dateFromString:self.dateTextField.text];
NSLog(#"%#", date);
}
Like this works for me:
- (void)dateTextFieldShouldReturn
{
NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_GB"]];
[formatter setDateFormat:#"EEE, dd MMM yyyy HH:mm:ss zzz"];
NSString* dateString = [formatter stringFromDate:self.datePicker.date];
[self.dateTextField setText:dateString];
[self.dateTextField resignFirstResponder];
NSDate* date = [formatter dateFromString:self.dateTextField.text];
NSLog(#"%#", date);
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
if (textfield1) {
NSString *txt = self.textfield1.text;
double num1 = [txt doubleValue];
double tCost = num1 /100;
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:tCost]];
self.textfield1.text = [NSString stringWithFormat:#"%0.#",numberAsString];
}
}
This is the code ive put together it formats the output of a textfield into currency
im trying to work out how do format the currency so the output is,
if someone types in 1625 it formats it as 0.1625
currently if somone types in 50 it formats it as 0.50 which is correct as it supposed to be a calculator which is taking in peoples electricity rates which is either in cents or pences.
To get currency formatting use the following code :
- (NSString*) getAmountInCurrencyFormatWithValue:(NSString*) valueString {
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:[valueString doubleValue]]];
return numberAsString;
}
(void)textFieldDidEndEditing:(UITextField *)textField
{
if (textfield1) {
NSString *txt = self.textfield1.text;
double num1 = [txt doubleValue];
double tCost = num1/100;
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
// NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:tCost]];
//NSString *numberAsString = [numberFormatter stringFromNumber:
// [NSNumber numberWithDouble:[tCost doubleValue]]];
[numberFormatter setMaximumFractionDigits:3];
[numberFormatter setRoundingMode: NSNumberFormatterRoundUp];
NSString *numberString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:tCost]];
self.textfield1.text = [NSString stringWithFormat:#"%#",numberString];
}
}