我有一个使用键盘的 OpenGL ES 应用程序。触摸屏幕时,我可以使键盘在屏幕上弹出。如果我是正确的,每次我按下一个键,
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
应该调用。但事实并非如此。该应用程序最初是一个纯 OpenGL Mac 游戏,我正在尝试制作 iOS 版本,所以我没有使用情节提要。如果可能的话,我更喜欢以编程方式做所有事情。这是我的 ViewController.h 代码:
#import <GLKit/GLKit.h>
#import "KeyboardView.h"
@interface ViewController : GLKViewController {
KeyboardView* keyBoard;
}
@end
ViewController.m 的相关部分:
- (void)viewDidLoad
{
[super viewDidLoad];
self.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
if (!self.context) {
NSLog(@"Failed to create ES context");
}
GLKView *view = (GLKView *)self.view;
view.context = self.context;
view.drawableDepthFormat = GLKViewDrawableDepthFormat24;
CGRect viewRect = CGRectMake(0, 0, 100, 100);
keyBoard = [[KeyboardView alloc] initWithFrame:viewRect];
[self setupGL];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self.view addSubview:keyBoard];
[keyBoard becomeFirstResponder];
}
键盘视图.h:
#import <UIKit/UIKit.h>
@interface KeyboardView : UIView <UIKeyInput, UITextFieldDelegate> {
UITextField *field;
}
键盘视图.m:
#import "KeyboardView.h"
@implementation KeyboardView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
field = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 100, 10)];
}
return self;
}
- (void)insertText:(NSString *)text {
}
- (void)deleteBackward {
}
- (BOOL)hasText {
return YES;
}
- (BOOL)canBecomeFirstResponder {
return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSLog(@"text: %@", textField.text);
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if ([newString length] < 1) {
return YES;
} else
{
textField.text = [newString length] > 1 ? [newString substringToIndex:1] : newString;
[textField resignFirstResponder];
return NO;
}
}
@end
我需要能够在键盘处于活动状态时获取用户输入的每个字符。我承认,我有点困惑。我不确定我的方法是否正确,因此非常感谢您的帮助。