在自定义视图中,您必须添加零大小的UITextField,然后将视图设置为其委托.然后在您的自定义视图中定义手势识别器(例如单击)并在手势识别器识别事件中将文本字段设置为第一响应者.点击视图后,键盘将弹出.然后编写委托方法:
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
Run Code Online (Sandbox Code Playgroud)
管理与键入的字符串的交互.如果您需要在用户键盘输入上更新视图,请不要忘记调用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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
915 次 |
| 最近记录: |