是否有一些可以手动显示键盘的ios API

时间:2011-08-09 08:23:49

标签: ios input keyboard

我有一个自定义视图,我希望显示一个键盘作为我的输入并与之互相通信。

谢谢你们〜

2 个答案:

答案 0 :(得分:5)

在自定义视图中,您必须添加零大小的UITextField,然后将视图设置为其委托。然后在您的自定义视图中定义手势识别器(例如,单击)并且在手势识别器识别事件中将文本字段设置为第一响应者。 点击视图后,键盘将弹出。然后编写委托方法:


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

管理与键入字符串的交互。如果您需要在用户键盘输入上更新视图,请不要忘记调用setNeedsDisplay。

以下示例有效。您必须在视图控制器中实例化自定义视图。使用该示例,只需在键盘中键入一个字母,它就会显示在视图上。



//
//  MyView.h
//

#import 

@interface MyView : UIView {

    UITextField *tf;

}

@property (nonatomic,copy) NSString *typed;

@end

//
//  MyView.m
//

#import "MyView.h"

@implementation MyView

@synthesize typed;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.backgroundColor=[UIColor redColor];
        tf = [[UITextField alloc] initWithFrame:CGRectZero];
        tf.delegate=self;
        [self addSubview:tf];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
        [self addGestureRecognizer:tap];
    }
    return self;
}


// Only override drawRect: if you perform custom drawing.
- (void)drawRect:(CGRect)rect
{
    // Draw the "typed" string in the view
    [[UIColor blackColor] setStroke];
    if(self.typed) {
        [self.typed drawAtPoint:CGPointZero withFont:[UIFont systemFontOfSize:50]];
    }
}


-(void)tap:(UIGestureRecognizer *)rec {
    if(rec.state==UIGestureRecognizerStateEnded) {
        [tf becomeFirstResponder];
    }
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    self.typed=[string substringToIndex:1]; // extract the first character of the string
    [self setNeedsDisplay]; // force view redraw
}

@end

答案 1 :(得分:0)

我认为解决方案可以像在您的班级中实施UIKeyInput协议一样简单。

详细了解 UIKeyInput Protocol Reference