is there some API of ios that can display keyboard manually
I have a custom view, i want display a keyboard as my input and int开发者_开发技巧ercommunicate with it.
thanks guys~
In your custom view you must add a zero-sized UITextField and then set your view as its delegate. Then in your custom view define a gesture recognizer (e.g. a single tap) and in the gesture recognizer recognition event set the text field as first responder. As soon as you tap the view the keyboard will popup. Then write the delegate method:
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
to manage the interaction with the typed string. Don't forget to call setNeedsDisplay if you need to update your view on the user keyboard typing.
The example below works. You must instantiate the custom view in your view controller of course. With the example, just type a letter in the keyboard and it will be displayed on the view.
//
// 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
I think the solution could be as simple as implementing the UIKeyInput
protocol in your class.
Read more about the UIKeyInput Protocol Reference.
精彩评论