我有一个自定义视图,我想在输入中显示一个键盘并与之交互。
谢谢大家〜
最佳答案
在自定义视图中,必须添加大小为零的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