I’m learning obj-c and gave myself a simple task of creation an app that has 2 uitextfields, label & button (button summarizes 2 numbers and shows the result in label). I made this app but I haven’t figured out how to make textfields interact with “done” button & “numbers only” together.
Below is my code:
#import UIKit/UIKit.h
@interface ViewController : UIViewController
@property IBOutlet UILabel *label;
@property IBOutlet UITextField *textField1;
@property IBOutlet UITextField *textField2;
@property NSInteger textFieldInt1, textFieldInt2;
@property NSString *textFieldStr1, *textFieldStr2;
-(IBAction)button:(id)sender;
-(IBAction)hideKeyboard:(id)sender;
@end
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize label, textField1, textField2, textFieldInt1, textFieldInt2, textFieldStr1, textFieldStr2;
-(IBAction)button:(id)sender {
textFieldInt1=[textField1.text integerValue];
textFieldInt2=[textField2.text integerValue];
label.text=[NSString stringWithFormat: @"%d", textFieldInt1+textFieldInt2];
[self.view endEditing:YES];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.textField1 setReturnKeyType:UIReturnKeyDone];
[self.textField2 setReturnKeyType:UIReturnKeyDone];
}
-(IBAction)hideKeyboard:(id)sender
{
[self.view endEditing:YES];
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if(![string intValue] && ![string isEqualToString:@""] && ![string isEqualToString:@"0"])
{
return NO;
} else {
return YES;
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[self.view endEditing:YES];
[super touchesBegan:touches withEvent:event];
}
@end
Also I connected (in storyboard) both textFields to hideKeyboard (didEndOnExit), and button to button (touchUpInside) and all outlets (textfields, button, label).
The problem is: numbers only input doesn’t work with done. If I use delegate (new referencing outlet in storyboard connected to both textfields) I get numbers only input in textfields but the done button doesn’t work (when I press it on the iPhone nothing happens). If I don’t use delegate I get all characters input but done works fine (when I press it iPhone keyboard hides).
Any suggestions what I may be doing wrong here?
Implement the UITextFieldDelegate method:
This tells the keyboard to hide when the done button is pressed.
Be sure to set your view controller as the textfields’ delegate:
myTextField.delegate = self;
(probably in viewDidLoad)