【问题标题】:is there some API of ios that can display keyboard manually是否有一些可以手动显示键盘的ios API
【发布时间】:2011-08-09 08:23:49
【问题描述】:

我有一个自定义视图,我想显示一个键盘作为我的输入并与之交互。

谢谢大家~

【问题讨论】:

  • 我知道UIKit中的UIView可以让键盘可见,但是我的view跟UIView没有关系,甚至是UIresponder。
  • 你的自定义视图怎么和 UIView 无关?

标签: ios input keyboard


【解决方案1】:

在您的自定义视图中,您必须添加一个大小为零的 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

【讨论】:

  • 真的很有用,而且效果很好。感谢您花时间这样做:)
【解决方案2】:

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

详细了解 UIKeyInput Protocol Reference

【讨论】:

    猜你喜欢
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-25
    • 1970-01-01
    • 2016-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多