业精于勤,荒于嬉
全部博文(763)
分类: C/C++
2010-02-08 15:40:39
想在你的游戏或应用程序中,改变一下你键盘的形象或定制特殊的键盘,方法很简单。我编写了一个简单程序将键盘上的Q键改为!键(由于photoshop水平有限,不是很完美,见谅!)
思路如下:
1. 键盘出现前都会系统会发出通知,我们要做的就是截取此事件,然后获得UIKeyboard对象:
1 |
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; |
2. 获取UIKeyboard对象。UIKeyboard处于UIWindow中。但是要注意的是,它并不处于当前应用程序的UIWindow中。所以我们必须通过一个循环来查找所需的UIWindow,从而获得UIKeyboard。然后替换或添加UIButton作为定制的按键:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
- (void)keyboardWillShow:(NSNotification *)notification { UIWindow* tmpWindow; UIView* keyboard; // Check each window in our application for(int i = 0; i < [[[UIApplication sharedApplication] windows] count]; i++) { // Get a reference of the current window tmpWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:i]; for(int j = 0; j < [tmpWindow.subviews count]; j++) { keyboard = [tmpWindow.subviews objectAtIndex:j]; // From all the apps i have made, they keyboard view description always starts with { UIButton* key = [UIButton buttonWithType:UIButtonTypeCustom]; // Position the button - I found these numbers align fine (0, 0 = top left of keyboard) key.frame = CGRectMake(2, 10, 31, 46); // Add images to our button so that it looks just like a native UI Element. [key setImage:[UIImage imageNamed:@"key.png"] forState:UIControlStateNormal]; [key setImage:[UIImage imageNamed:@"key-pressed.png"] forState:UIControlStateHighlighted]; //Add the button to the keyboard [keyboard addSubview:key]; // When the decimal button is pressed, we send a message to ourself (the AppDelegate) which will then post a notification that will then append a decimal in the UITextField in the Appropriate View Controller. [key addTarget:self action:@selector(keypressed:) forControlEvents:UIControlEventTouchUpInside]; return; } } } } |
3. 捕获UIButton事件,实现你自己的逻辑。比如,在我的程序中,当用户按下!键后,我会将!输入到UITextView中:
1 2 3 |
- (void)keypressed:(id)sender{ textView.text = [textView.text stringByAppendingString:@"!"]; } |
这里是。