我正在学习obj-c并给自己一个简单的任务,即创建一个有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键盘隐藏时)。
有什么建议我可能在这里做错了吗?
答案 0 :(得分:0)
实现UITextFieldDelegate方法:
// This is how we get rid of the keyboard.
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
//Do whatever you need to to save etc...
[textField resignFirstResponder];
return NO;
}
这告诉键盘在按下完成按钮时隐藏。 务必将视图控制器设置为文本字段的委托: myTextField.delegate = self; (可能在viewDidLoad中)