iOS 之UITextFiled/UITextView小结

一:编辑被键盘遮挡的问题    (推荐使用第三方库:IQKeyboardManager  用法参考

 参考自:http://blog.csdn.net/windkisshao/article/details/21398521

1.自定方法 ,用于移动视图

-(void)moveInputBarWithKeyboardHeight:(float)_CGRectHeight withDuration:(NSTimeInterval)_NSTimeInterval;

2.注册监听

NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];

    [defaultCenter selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

    [defaultCenter addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

3.实现方法

- (void)keyboardWillShow:(NSNotification *)notification {

    NSDictionary *userInfo = [notification userInfo];

    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];

    CGRect keyboardRect = [aValue CGRectValue];

    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];

    NSTimeInterval animationDuration;

    [animationDurationValue getValue:&animationDuration];

    if(nil==self.myTextView) return;//    self.editTextView 为被键盘遮挡住的控件

    CGRect rect = self.myTextView.frame;

    float textY = rect.origin.y + rect.size.height; 

    float bottomY = SCREENHEIGHT - textY;//得到下边框到底部的距离  SCREENHEIGHT 为当前设备的高度

    if(bottomY >=keyboardRect.size.height ){//键盘默认高度,如果大于此高度,则直接返回

        return;

    }

    float moveY = keyboardRect.size.height - bottomY;

    [self moveInputBarWithKeyboardHeight:moveY withDuration:animationDuration];

}

 

- (void)keyboardWillHide:(NSNotification *)notification {

    NSDictionary* userInfo = [notification userInfo];

    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];

    NSTimeInterval animationDuration;

    [animationDurationValue getValue:&animationDuration];

    [self moveInputBarWithKeyboardHeight:0.0 withDuration:animationDuration];

}

 

-(void)moveInputBarWithKeyboardHeight:(float)_CGRectHeight withDuration:(NSTimeInterval)_NSTimeInterval{

  CGRect rect1 = self.view.frame;

    [UIView beginAnimations:nil context:NULL];

    [UIView setAnimationDuration:_NSTimeInterval];

    rect1.origin.y = -_CGRectHeight;//view往上移动

    self.view.frame = rect1;

    [UIView commitAnimations];

}

二: 键盘

(1)键盘类型 

     UIKeyboardTypeDefault, // 默认键盘:支持所有字符 

  1.  UIKeyboardTypeASCIICapable, // 支持ASCII的默认键盘 
  2.  UIKeyboardTypeNumbersAndPunctuation, // 标准电话键盘,支持+*#等符号 
  3.  UIKeyboardTypeURL, // URL键盘,有.com按钮;只支持URL字符 
  4.  UIKeyboardTypeNumberPad,  //纯数字键盘 (不带小数点)
  5.  UIKeyboardTypeDecimalPad  //数字键盘 (带小数点)
  6.  UIKeyboardTypePhonePad,   // 电话键盘 
  7.  UIKeyboardTypeNamePhonePad, // 电话键盘,也支持输入人名字 
  8.  UIKeyboardTypeEmailAddress, // 用于输入电子邮件地址的键盘
  9.  UIKeyboardTypeWebSearch     //用于搜索
  10. UIKeyboardTypeAlphabet

   如:  self.uIphone.keyboardType = UIKeyboardTypeNumberPad;

   祥见:http://blog.csdn.net/crazyzhang1990/article/details/39965931

(2) return键的类型 

       UIReturnKeyDefault, 默认 灰色按钮,标有Return 

     UIReturnKeyGo,     标有Go的蓝色按钮           (完成,可用于填写资料的最后一项)

     UIReturnKeyGoogle,标有Google的蓝色按钮,用语搜索 

     UIReturnKeyJoin,标有Join的蓝色按钮 

     UIReturnKeyNext,标有Next的蓝色按钮             (可用于登录/注册/填写地址-->下一步)

     UIReturnKeyRoute,标有Route的蓝色按钮 

     UIReturnKeySearch,标有Search的蓝色按钮     (可用于搜索)

     UIReturnKeySend,标有Send的蓝色按钮          

     UIReturnKeyYahoo,标有Yahoo的蓝色按钮 

     UIReturnKeyYahoo,标有Yahoo的蓝色按钮 

     UIReturnKeyEmergencyCall, 紧急呼叫按钮

  如:

 self.uIphone.keyboardType = UIKeyboardTypeNumberPad;

(3) 点击return建响应事件

   A.UITextField --> - (BOOL)textFieldShouldReturn:(UITextField *)textField{

   如:  添加地址

- (BOOL)textFieldShouldReturn:(UITextField *)textField{

    if(textField.tag==10)  //下一步 (姓名)

    {

        [self.uName resignFirstResponder];

        [self.uIphone becomeFirstResponder];

    }else if(textField.tag==11)   //下一步 (电话)

    {

        [self.uIphone resignFirstResponder];

        [self.reciveAddress becomeFirstResponder];

    }else if(textField.tag==100)   //完成(地址填完之后可直接调用接口)

    {

        [self.reciveAddress resignFirstResponder];

         [self addBtn:nil];     

    }

    return YES;

}

B.UITextView --> - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

如:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]){ //判断输入的字是否是回车,即按下return
        //在这里做你响应return键的代码

         [self addBtn:nil];

        return NO; //这里返回NO,就代表return键值失效,即页面上按下return,不会出现换行,如果为yes,则输入页面会换行
    }

    return YES;
}

参考自:http://blog.sina.com.cn/s/blog_59fb90df010176re.html

 

三:UITextField小结

   1.自定义UITextField 左边加图标(如:登录)

    UIImageView *i=[[UIImageView alloc]initWithFrame:CGRectMake(15, 10, 21, 21)];

    [i setImage:[UIImage imageNamed:@"yh"]];

    UIView *userLeftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 40, 38)];

    [userLeftView addSubview:i]; 

    self.userName.leftView=userLeftView;

    self.userName.leftViewMode=UITextFieldViewModeAlways;

     若只是单纯的UITextField 缩进: 只需加  self.userName.leftViewMode=UITextFieldViewModeAlways; self.userName.leftView=[[UIView alloc]init] 两句即可。

   2.设置自定义UITextField 的Placeholder颜色   

   (1)方法一:

       UIColor *color = [UIColor blue];

    self.userName.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"  手机号"  attributes:@{NSForegroundColorAttributeName: color}];

(2)方法二:        

   [textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"]; 

   [textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];

   3.统一收起键盘      

    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];

    4. textFiled  自动换行           

          http://blog.csdn.net/u012661893/article/details/52183456

四:UITextView小结

  1.设置Placeholder      

    @property (nonatomic,strong) UILabel  *proText1;        

    self.automaticallyAdjustsScrollViewInsets = NO;    

    [self.leaveMessage setDelegate:self];

    UILabel *lbl=[[UILabel alloc]initWithFrame:CGRectMake(self.leaveMessage.frame.origin.x+10, self.leaveMessage.frame.origin.y-35, self.leaveMessage.bounds.size.width, 100)];

    lbl.text=@" 感谢您留下宝贵的意见....";

    [lbl setFont:[UIFont systemFontOfSize:15.0]];

    lbl.enabled=NO;

    self.proText1=lbl;

    [self.view addSubview:lbl];    

  #pragma mark -----textView的代理事件

  -(void)textViewDidChange:(UITextView *)textView

  {

   //  textView.text = [textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

        if (textView.text.length == 0) {

            self.proText1.text = @" 感谢您留下宝贵的意见....";

        }else{

            self.proText1.text = @"";

        }

  }

2.去掉空格以及换行

 NSString *content = [textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

有的时候由于不正确的操作,直接将textView.text作为参数传 到服务器,可能会产生意想不到的错误,因此就需要加这个对字符串进行一下处理

 

3. 限制输入长度

    实现代理方法:

- (void)textViewDidChange:(UITextView *)textView{

     NSString *toBeString = [textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

    //获取高亮部分

    UITextRange *selectedRange = [textView markedTextRange];

    UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];

    

    // 没有高亮选择的字,则对已输入的文字进行字数统计和限制

    if (!position)

    {

        if (toBeString.length > MAX_STARWORDS_LENGTH)

        {

            [MBProgressHUD showAlert:@"最多只能输入150个字。"];

            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:MAX_STARWORDS_LENGTH];

            if (rangeIndex.length == 1)

            {

                textView.text = [toBeString substringToIndex:MAX_STARWORDS_LENGTH];

            }

            else

            {

                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, MAX_STARWORDS_LENGTH)];

                textView.text = [toBeString substringWithRange:rangeRange];

            }

        }

    }

}

 

 

 更多请参考:http://www.41443.com/HTML/iphone/20141109/204260.html

 

补充:   

1.长按复制功能

 - (void)viewDidLoad { 

     [self.view addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(pasteBoard:)]]; 

}

 - (void)pasteBoard:(UILongPressGestureRecognizer *)longPress { 

          if (longPress.state == UIGestureRecognizerStateBegan) {

                             UIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; 

                              pasteboard.string = @"需要复制的文本";

          } }

 

2.导入自定义字体库

     1、找到你想用的字体的 ttf 格式,拖入工程

     2、在工程的plist中增加一行数组,“Fonts provided by application”

     3、为这个key添加一个item,value为你刚才导入的ttf文件名

     4、直接使用即可:label.font = [UIFont fontWithName:@"你刚才导入的ttf文件名" size:20.0];

 附:计算文字的size

/**
 *  计算一段文字size
 */
- (CGSize)sizeWithFont:(UIFont *)font maxW:(CGFloat)maxW
{
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = font;
    CGSize maxSize = CGSizeMake(maxW, MAXFLOAT);
    
    return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
    
}
/**
 *  计算一行文字size
 */
- (CGSize)sizeWithFont:(UIFont *)font
{
    return [self sizeWithFont:font maxW:MAXFLOAT];
}

 

转载于:https://www.cnblogs.com/Cyan-zoey/p/5133167.html

你可能感兴趣的:(iOS 之UITextFiled/UITextView小结)