iOS UITextView UITextField 小知识大全

转自:http://blog.csdn.net/ysy441088327/article/details/7625000

1:禁止 UITextView 拖动

[csharp] view plain copy
  1. textView.scrollEnabled = NO;  

注:如果动态修改textView的Frame时,不设置为NO,输入光标的显示位置将不会友好.

2: - (void)textViewDidChangeSelection:(UITextView *)textView



修改光标位置代码:

[csharp] view plain copy
  1. NSRange range;  
  2. range.location = 0;  
  3. range.length = 0;  
  4. textView.selectedRange = range;  


注:手动调整光标位置时触发的委托,在第一次启动TextView编辑时,也会触发,会优先于键盘启动观察者事件,可以在这里区别是哪个TextView启动了键盘.

     本委托的优先执行率高于 textViewDidBeginEditing 代理 也高于 UIKeyboardWillShowNotification 通知

3:监听TextView 点击了ReturnKey 按钮

[csharp] view plain copy
  1. - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text  
  2. {  
  3.   
  4.     if ([text isEqualToString:@"\n"]) {  
  5.           
  6.         //这里写按了ReturnKey 按钮后的代码  
  7.         return NO;  
  8.     }  
  9.   
  10.     return YES;  
  11. }  

4:为UITextView 添加 Placeholder

[csharp] view plain copy
  1. #import <UIKit/UIKit.h>  
  2.   
  3. @interface FEUITextView : UITextView  
  4.   
  5. @property(nonatomic) UILabel *placeHolderLabel;  
  6. @property(nonatomic) NSString *placeholder;  
  7. @property(nonatomic) UIColor *placeholderColor;  
  8.   
  9.   
  10. @end  


[csharp] view plain copy
  1. - (id)initWithCoder:(NSCoder *)aDecoder  
  2. {  
  3.     self = [super initWithCoder:aDecoder];  
  4.     if (self) {  
  5.         [self FE_defaultFunction];  
  6.     }  
  7.     return self;  
  8. }  
  9.  
  10.  
  11. #pragma mark - Private Function  
  12. - (void)FE_defaultFunction  
  13. {  
  14.     [self setText:@""];  
  15.     [self.layer setBorderWidth:1.0f];  
  16.     [self.layer setBorderColor:[UIColor colorWithRed:196.0/255.0 green:196.0/255.0 blue:196.0/255.0 alpha:1.0].CGColor];  
  17.     [self.layer setCornerRadius:5.0f];  
  18.     [self setBackgroundColor:[UIColor whiteColor]];  
  19.       
  20.     [self setPlaceholder:@""];  
  21.     [self setPlaceholderColor:[UIColor lightGrayColor]];  
  22.     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(FE_textChanged:) name:UITextViewTextDidChangeNotification object:nil];  
  23. }  
  24. - (void)FE_textChanged:(NSNotification *)notification  
  25. {  
  26.     if([[self placeholder] length] == 0)  
  27.     {  
  28.         return;  
  29.     }  
  30.     if([[self text] length] == 0)  
  31.     {  
  32.         [[self viewWithTag:999] setAlpha:1];  
  33.     }  
  34.     else  
  35.     {  
  36.         [[self viewWithTag:999] setAlpha:0];  
  37.     }  
  38. }  
  39. - (void)setText:(NSString *)text {  
  40.     [super setText:text];  
  41.     [self FE_textChanged:nil];  
  42. }  
  43. - (void)drawRect:(CGRect)rect  
  44. {  
  45.     if( [[self placeholder] length] > 0 )  
  46.     {  
  47.         if ( placeHolderLabel == nil )  
  48.         {  
  49.             placeHolderLabel = [[UILabel alloc] initWithFrame:CGRectMake(8,8,self.bounds.size.width - 16,0)];  
  50.             placeHolderLabel.lineBreakMode = UILineBreakModeWordWrap;  
  51.             placeHolderLabel.numberOfLines = 0;  
  52.             placeHolderLabel.font = self.font;  
  53.             placeHolderLabel.backgroundColor = [UIColor clearColor];  
  54.             placeHolderLabel.textColor = self.placeholderColor;  
  55.             placeHolderLabel.alpha = 0;  
  56.             placeHolderLabel.tag = 999;  
  57.             [self addSubview:placeHolderLabel];  
  58.         }  
  59.         placeHolderLabel.text = self.placeholder;  
  60.         [placeHolderLabel sizeToFit];  
  61.         [self sendSubviewToBack:placeHolderLabel];  
  62.     }  
  63.     if( [[self text] length] == 0 && [[self placeholder] length] > 0 )  
  64.     {  
  65.         [[self viewWithTag:999] setAlpha:1];  
  66.     }  
  67.     [super drawRect:rect];  
  68. }  

5:键盘启动监听

[csharp] view plain copy
  1. //视图成功展现出来以后调用  
  2. - (void)viewDidAppear:(BOOL)animated  
  3. {  
  4.     //监听键盘切换  
  5.     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(FE_keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];  
  6.     [self.coopRemarkTextView becomeFirstResponder];  
  7. }  
  8. //视图准备回收时调用  
  9. - (void)viewWillDisappear:(BOOL)animated  
  10. {  
  11.     [self.coopRemarkTextView resignFirstResponder];  
  12.     [UIView animateWithDuration:0.25 delay:0 options:0 animations:^{  
  13.         [self.coopRemarkTextView setHelp_height:1];  
  14.     } completion:^(BOOL finished) {  
  15.     }];  
  16.     [[NSNotificationCenter defaultCenter] removeObserver:self];  
  17. }  
  18.   
  19. /** 
  20.  *  @brief  当系统键盘被使用是触发此通知 
  21.  * 
  22.  *  @param  notification    通知 
  23.  */  
  24. - (void)FE_keyboardWillShow:(NSNotification*)notification {  
  25.         NSDictionary *userInfo = [notification userInfo];  
  26.         NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];  
  27.         CGRect keyboardRect = [aValue CGRectValue];  
  28.         CGRect keyboardFrame = [self.view convertRect:keyboardRect fromView:[[UIApplication sharedApplication] keyWindow]];  
  29.         CGFloat  keyboardHieght =keyboardFrame.size.height ;//这里记录键盘启动或者是切换其他类型的键盘时 当前View相对键盘的Y轴  
  30.         [UIView animateWithDuration:0.25 delay:0 options:0 animations:^{  
  31.             [self.coopRemarkTextView setHelp_height:self.view.Help_height - keyboardHieght-24];  
  32.         } completion:^(BOOL finished) {  
  33.         }];  
  34. }  


---------------------------------------------------------------------------------UITextView---------------------------------------------------------------------------------------

---------------------------------------------------------------------------------UITextField---------------------------------------------------------------------------------------

1: 监听 UITextField 值变动事件

[csharp] view plain copy
  1. [searchTextField addTarget:self action:@selector(FE_fieldValueChange:) forControlEvents:UIControlEventEditingChanged];  

2:将输入值显示成保密状态

[csharp] view plain copy
  1. self.password.secureTextEntry = YES;  

3:修改UITextField 输入光标的边距(类似Padding的概念)位置(参考:UITextField设置padding)

[csharp] view plain copy
  1. - (void)Parent_setTextCursorWithLeftPadding:(CGFloat)paddingLeft withRightPadding:(CGFloat)paddingRight  
  2. {  
  3.     self.Parent_paddingLeft = paddingLeft;  
  4.     self.Parent_paddingRight = paddingRight;  
  5. }  
  6. - (CGRect)textRectForBounds:(CGRect)bounds {  
  7.     return CGRectMake(bounds.origin.x + self.Parent_paddingLeft,  
  8.                       bounds.origin.y ,  
  9.                       bounds.size.width - self.Parent_paddingRight, bounds.size.height);  
  10. }  
  11. - (CGRect)editingRectForBounds:(CGRect)bounds {  
  12.     return [self textRectForBounds:bounds];  
  13. }  

4:去掉键盘输入时的辅助提示

[csharp] view plain copy
  1. self.testTextField.autocorrectionType = UITextAutocorrectionTypeNo;  

5:设置UITextField在空值时禁止Return Key的使用
[csharp] view plain copy
  1. self.testTextField.enablesReturnKeyAutomatically = YES;  

6:设置键盘风格
[csharp] view plain copy
  1. self.testTextField.keyboardAppearance = UIKeyboardAppearanceAlert;//黑色风格 目前只有两种  

7:为UITextField加入清除输入值按钮

[csharp] view plain copy
  1. [_flowCalendarTimeInputView setClearButtonMode:UITextFieldViewModeWhileEditing];  

8:修复UITextField 当前光标所在位置 (参考:光标移动)

[csharp] view plain copy
  1. - (void)Help_moveCursorWithDirection:(UITextLayoutDirection)direction offset:(NSInteger)offset  
  2. {  
  3.     UITextRange *range = self.selectedTextRange;  
  4.     UITextPosition* start = [self positionFromPosition:range.start inDirection:direction offset:offset];  
  5.     if (start)  
  6.     {  
  7.         [self setSelectedTextRange:[self textRangeFromPosition:start toPosition:start]];  
  8.     }  
  9. }  

注:1:所入光标移动的方向 和  位置值

     2:如果需要在键盘刚启动时就修改键盘光标位置请在  becomeFirstResponder前调用

[csharp] view plain copy
  1. [_flowCalendarTimeInputView becomeFirstResponder];  
  2. [_flowCalendarTimeInputView Help_moveCursorWithDirection:UITextLayoutDirectionLeft offset:1];  

9:基于第八点技术实现手工输入时间数字校验代码:

第一步: 先设置委托和监听

[csharp] view plain copy
  1. [_flowCalendarTimeInputView setDelegate:self];  
  2. [_flowCalendarTimeInputView addTarget:self action:@selector(Flow_inputTimeValueChange:) forControlEvents:UIControlEventEditingChanged];  
第二步:实现
[csharp] view plain copy
  1. - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string  
  2. {  
  3.     if ([string isEqualToString:@""]) {  
  4.         return NO;  
  5.     }  
  6.     switch (textField.text.length) {  
  7.         case 1:  
  8.             if ([string  intValue] > 2) {  
  9.                 return NO;  
  10.             }  
  11.             break;  
  12.         case 2:  
  13.             if ([string  intValue] > 3) {  
  14.                 return NO;  
  15.             }  
  16.             break;  
  17.         case 3:  
  18.             if ([string  intValue] > 5) {  
  19.                 return NO;  
  20.             }  
  21.             break;  
  22.         case 4:  
  23.               
  24.             break;  
  25.         default:  
  26.             break;  
  27.     }  
  28.     return YES;  
  29. }  
  30. - (void)Flow_inputTimeValueChange:(UITextField *)textField  
  31. {  
  32.     if (textField.text.length == 0) {  
  33.         [textField setText:@":"];  
  34.         [textField Help_moveCursorWithDirection:UITextLayoutDirectionLeft offset:1];  
  35.     }  
  36.     if (textField.text.length == 5) {  
  37.         [self setFlowCalendarSelectedDate:[NSDate Help_dateWithDateString:[NSString stringWithFormat:@"2012-11-01 %@:00",textField.text]] modifyMode:FlowCalendarSelectedDateModifyModeTime];  
  38.     }  
  39.     if (textField.text.length >= 6) {  
  40.         textField.text = [textField.text substringWithRange:(NSRange){0,textField.text.length-1}];  
  41.     }  
  42.     if (textField.text.length == 3) {  
  43.         [textField Help_moveCursorWithDirection:UITextLayoutDirectionRight offset:1];  
  44.     }  
  45. }  

10:为 键盘类型: UIKeyboardTypeNumberPad 添加 完成按钮(参考:http://www.winddisk.com/2012/04/06/uikeyboardtypenumberpad_add_returnkey/)

 一:注册监听事件:

[csharp] view plain copy
  1. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Flow_keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];  

[csharp] view plain copy
  1. /** 
  2.  *  @brief  当系统键盘展现出来以后触发此通知 
  3.  * 
  4.  *  @param  notification    通知 
  5.  */  
  6. - (void)Flow_keyboardDidShow:(NSNotification*)notification {  
  7.     [self Flow_addFinishButtonToKeyboard];  
  8. }  
那么当键盘展现出来时,就会触发这个方法:

二:添加完成按钮方法:

[csharp] view plain copy
  1. - (void)Flow_addFinishButtonToKeyboard {  
  2.     // create custom button  
  3.     UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];  
  4.     doneButton.frame = CGRectMake(0, 163, 106, 53);  
  5.     doneButton.adjustsImageWhenHighlighted = NO;  
  6.     [doneButton setImage:[UIImage imageNamed:@"DoneUp3.png"] forState:UIControlStateNormal];  
  7.     [doneButton setImage:[UIImage imageNamed:@"DoneDown3.png"] forState:UIControlStateHighlighted];  
  8.     [doneButton addTarget:self action:@selector(Flow_finishSelectedAction:) forControlEvents:UIControlEventTouchUpInside];  
  9.     // locate keyboard view  
  10.     UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];  
  11.     UIView* keyboard;  
  12.     for(int i=0; i<[tempWindow.subviews count]; i++) {  
  13.         keyboard = [tempWindow.subviews objectAtIndex:i];  
  14.         if([[keyboard description] hasPrefix:@"<UIPeripheralHost"] == YES)  
  15.             [keyboard addSubview:doneButton];  
  16.     }  
  17. }  
找到keywindow后再依次找到键盘视图的原理

三:不使用的时候必须撤销这个键盘监听事件,否则影响其他视图键盘的使用

[csharp] view plain copy
  1. [[NSNotificationCenter defaultCenter] removeObserver:self];  

11:设置UITextField 水平居中,垂直居中

[csharp] view plain copy
  1. [_flowCalendarTimeInputView setTextAlignment:NSTextAlignmentCenter];  
  2. [_flowCalendarTimeInputView setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];  


---------------------------------------------------------------------------------UITextField---------------------------------------------------------------------------------------


  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值