我正在学习 obj-c 并给自己一个简单的任务,即创建一个具有 2 uitextfields
、label
&的应用程序button
(按钮汇总 2 个数字并在标签中显示结果)。我制作了这个应用程序,但我还没有弄清楚如何textfields
与“完成”按钮和“仅限数字”一起进行交互。
下面是我的代码:
#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
我还(在情节提要中)连接textFields
到hideKeyboard (didEndOnExit)
、 和button
以及button (touchUpInside)
所有出口(textfields
、button
、label
)。
问题是: numbers only
输入不适用于done
. 如果我使用delegate
(情节提要中的新引用插座连接到两者textfields
)我会numbers only
输入textfields
但done
按钮不起作用(当我在 iPhone 上按下它时没有任何反应)。如果我不使用delegate
我会得到all characters
输入但done
工作正常(当我按下它时 iPhone 键盘隐藏)。
有什么建议我可能在这里做错了吗?