1.在视图控制器中声明UITextField变量
#import <UIKit/UIKit.h>
//#import <UIKeyboard.h>
//#import <AppKit/NSEvent.h>
@interface keyboardViewController : UIViewController <UITextFieldDelegate> {
IBOutlet UITextField *txt;
}
@property (nonatomic,retain) UITextField *txt;
@end
2.打开viewDidLoad注释,加入如下代码:
- (void)viewDidLoad
{
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyPressed:) name: UITextFieldTextDidChangeNotification object: nil];
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyPressed:) name: UITextViewTextDidChangeNotification object: nil];
//We set the delegate so we can grab keypressed
txt=[[UITextField alloc] initWithFrame:CGRectZero];
txt.returnKeyType= UIReturnKeyDone;
txt.delegate = self;
[self.view addSubview:txt];
[txt becomeFirstResponder]; //Show the keyboard
[super viewDidLoad];
}
3.键盘响应函数
- (void)keyPressed:(NSNotification*)notification
{
NSLog(@"hello");
// NSLog([[notification object] text]);
NSString *str= [[NSString alloc] init];
str=[[notification object] text];
const char *cstring=[str UTF8String];
NSLog(@"%s",cstring);
}