如何在OpenGL es app中使用键盘

时间:2014-08-31 15:42:59

标签: ios objective-c opengl-es keyboard glkview

我有一个使用键盘的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];
}

KeyboardView.h:

#import <UIKit/UIKit.h>

@interface KeyboardView : UIView <UIKeyInput, UITextFieldDelegate> {
    UITextField *field;
}

KeyboardView.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

我需要能够在键盘处于活动状态时让用户输入每个字符。我最承认,我有点困惑。我不确定我的方法是否正确,所以我非常感谢你的帮助。

1 个答案:

答案 0 :(得分:1)

键盘文字输入未通过UITextField

获取

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

确实是通过UIKeyInput

获取的

- (void)insertText:(NSString *)text;

我正在使用软键盘在我的GLKView(OpenGLES)应用程序上捕获文本,我甚至根本不需要任何UITextField

供参考:

UIKeyInput Reference Doc

编辑:

您需要致电键盘浏览器becomeFirstResponder以显示键盘并致电resignFirstResponder隐藏

您还需要覆盖canBecomeFirstResponder并返回TRUE