我有一个简单的程序,您可以在其中在文本字段中输入文本,点击确定按钮,标签会随着输入的文本更新。
当我按下 OK 按钮、按下覆盖整个视图的背景中的大按钮或按下键盘上的返回按钮时,我希望 iPhone 键盘消失。我一直在尝试使用
[textField resignFirstResponder]
方法,但它不起作用。该程序编译得很好,但是当从这些事件中的任何一个调用此方法时,它就会停止,并且我收到一条消息:
线程 1:信号 SIGABRT"
我究竟做错了什么?
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize txtName;
@synthesize lblMessage;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)doSomething:(UIButton *)sender
{
[txtName resignFirstResponder];
NSString *msg = [[NSString alloc] initWithFormat:@"Hello, %@", txtName.text];
[lblMessage setText:msg];
//[msg release];
}
- (IBAction)makeKeyboardGoAway:(UIButton *)sender
{
[txtName resignFirstResponder];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
@end
这里也是头文件:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UITextField *txtName;
@property (weak, nonatomic) IBOutlet UILabel *lblMessage;
- (IBAction)doSomething:(UIButton *)sender;
- (IBAction)makeKeyboardGoAway:(UIButton *)sender;
@end
好吧,我让它工作了,但我仍然不明白我收到的错误消息。这是对我有用的代码。
标题:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
{
IBOutlet UITextField *txtName;
IBOutlet UILabel *lblMessage;
}
@property (nonatomic, retain) IBOutlet UITextField *txtName;
@property (nonatomic, retain) IBOutlet UILabel *lblMessage;
- (IBAction)doSomething;
- (IBAction)makeKeyboardGoAway;
@end
执行:
#import "ViewController.h"
@implementation ViewController
@synthesize txtName;
@synthesize lblMessage;
- (IBAction)doSomething
{
[txtName resignFirstResponder];
NSString *msg = [[NSString alloc] initWithFormat:@"Hello, %@",
txtName.text];
[lblMessage setText:msg];
//[msg release];
}
- (IBAction) makeKeyboardGoAway
{
[txtName resignFirstResponder];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end