iOS简易文本控件开发(UIKeyInput协议学习)
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
iOS简易⽂本控件开发(UIKeyInput协议学习)
有时候由于特殊原因,不想去⽤ios系统的默认输⼊控件如UITextView等,此时则需要⾃⼰定制⽂本控件。
下⾯步骤最后形成的控件,仅⽀持英⽂字符输⼊,其余功能⽐如插⼊符闪烁,⽂本选择等等都不具备!
1.⾸先,要新建⼀个继承UIView的类。
并声明如下⼏个类型的属性,⽤来记录⼀个⽂本控件内容:
1@interface SIPTextView : UIView<UIKeyInput>
2 {
3 NSMutableString *textStore;
4 UIFont *font;
5 UIColor *textColor;
6 }
7 @property (nonatomic, retain) NSMutableString *textStore;
8 @property (nonatomic, retain) UIColor *textColor;
9 @property (nonatomic, retain) UIFont *font;
在init⽅法中可以初始化这些数据:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor whiteColor];
self.textColor = [UIColor blackColor];
self.font = [UIFont boldSystemFontOfSize:12.0f];
self.textStore = [NSMutableString string];
}
return self;
}
2.接着让这个类实现协议UIKeyInput,协议声明详情如下:
@protocol UIKeyInput <UITextInputTraits>
- (BOOL)hasText;
- (void)insertText:(NSString *)text;
- (void)deleteBackward;
@end
协议中insertText⽅法会在⽤户在此控件有键盘输⼊时被调⽤,我们要在此记录输⼊的⽂本信息。
deleteBackward⽅法会在⽤户想按键删除⼀个输⼊字符时被调⽤,我们要在此删除⼀个字符:
#pragma mark UIKeyInput protocol
-(void)insertText:(NSString *)text {
[textStore appendString:text];
//呼唤重绘
[self setNeedsDisplay];
}
- (BOOL)hasText
{
return textStore.length > 0;
}
- (void)deleteBackward
{
if ([textStore length] == 0) {
return;
}
NSRange theRange = NSMakeRange(textStore.length - 1, 1);
[textStore deleteCharactersInRange:theRange];
//呼唤重绘
[self setNeedsDisplay];
}
由于默认情况下控件⽆法成为第⼀响应者,所以必须更改此设置,并让其在被点击时成为第⼀响应者:
1 - (BOOL)canBecomeFirstResponder {
2return YES;
3 }
4
5 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
6if (![self isFirstResponder]) {
7 [self becomeFirstResponder];
8 }
9 }
⽬前为⽌,此视图已经可以正常接收键盘输⼊消息了(可在insertText⽅法log出来看)。
3.最后⼀步是把存储了键盘输⼊信息的⽂本属性显⽰出来,重写视图的drawRect⽅法如下:
1 - (CGRect)rectForTextWithInset:(CGFloat)inset {
2return CGRectInset(self.bounds, inset, inset);
3 }
4
5 - (void)drawRect:(CGRect)rect {
6 CGRect rectForText = [self rectForTextWithInset:8.0f];
7//设置当前绘制颜⾊
8 [textColor set];
9//绘制矩形框边缘,UIRectFill(rect)则绘制矩形内部
10//UIRectFrame(rect);
11//⼀般⽤NSString的内置draw⽅法绘制⽂字
12 [textStore drawInRect:rectForText withFont:font];
13 }
以上就是定制简易⽂本控件所有步骤。
------------------------------------------------------------------------------------------------------------------------------------------------------
由于UIKeyInput协议遵循UITextInputTraits协议(此协议可以⾃⾏查阅其相关⽅法),因此也可以为这个视图设置键盘风格等,⽐如可以设置键盘类型为数字键盘:
1 - (UIKeyboardType)keyboardType {
2return UIKeyboardTypeNumberPad;
3 }
------------------------------------------------------------------------------------------------------------------------------------------------------
要实现⽀持中⽂输⼊,闪烁光标和选区功能的⽂本控件⽐较复杂,下次再写吧......。