iOS UITextField 使用全解

UITextField 座位用户交互的一个必备使用的控件,其使用频率较高。

定义一个UITextField 及其基本的属性:

UITextField _telNum = [[UITextField alloc] init];
    _telNum.clearsOnBeginEditing = NO;//在输入时不清除原来输入的文字
    _telNum.delegate = self;//
    [_telNum addTarget:self action:@selector(textFieldDoneEditing:) forControlEvents:UIControlEventEditingDidEndOnExit];//
 _telNum.font = [UIFont boldSystemFontOfSize:14];//
 _telNum.textColor = [UIColor blackColor];//
 _telNum.backgroundColor = [UIColor clearColor];//
 _telNum.borderStyle = UITextBorderStyleNone;
 _telNum.clearButtonMode = UITextFieldViewModeWhileEditing;
 _telNum.autocorrectionType = UITextAutocorrectionTypeNo;
 _telNum.autocapitalizationType  = UITextAutocapitalizationTypeNone;
 _telNum.returnKeyType = UIReturnKeyDefault;
 _telNum.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
 _telNum.placeholder = @"默认的文本";
    _telNum.keyboardType = UIKeyboardTypeNumberPad;//文本输入时,按键弹出的按键为数字

下面为UITextField 的一些代理方法:

1.开始输入文本时,一般需要判断键盘是否遮挡住了UITextField 视图,是的话需要调整整个视图的位置。

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
   
    CGRect textFrame =  textField.frame;
    float textY = textFrame.origin.y+textFrame.size.height;
    float bottomY = self.view.frame.size.height-textY;
    if(bottomY<216)  //判断当前的高度是否已经有216,如果超过了就不需要再移动主界面的View高度
    {
        float moveY = 216-bottomY;
        prewMoveY = moveY;
   
        NSTimeInterval animationDuration = 0.30f;
        CGRect frame = self.view.frame;
        frame.origin.y -=moveY;//view的Y轴上移
        frame.size.height +=moveY; //View的高度增加
        self.view.frame = frame;
        [UIView beginAnimations:@"ResizeView" context:nil];
        [UIView setAnimationDuration:animationDuration];
        self.view.frame = frame;
        [UIView commitAnimations];//设置调整界面的动画效果
    }
    return YES;
}

2. 输入文本结束时,调回输入前的视图布局

-(void ) textFieldDoneEditing:(id) sender{
 if (sender == _telNum) {
  _payButton.enabled = YES;
       
        NSTimeInterval animationDuration = 0.30f;
        CGRect frame = self.view.frame;
        //还原界面
        frame.origin.y +=prewMoveY;
        frame.size. height -=prewMoveY;
        self.view.frame = frame;
        //self.view移回原位置
        [UIView beginAnimations:@"ResizeView" context:nil];
        [UIView setAnimationDuration:animationDuration];
        self.view.frame = frame;
        [UIView commitAnimations];
        [sender resignFirstResponder];
       
 }
}

3.决定文本输入的字数,超过一定的范围则弹出提示框:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (range.location>=11)
    {
        alertMessage(nil, @"超过了电话号码的长度!");
        return  NO;
    }
    else
    {
        return YES;
    }
}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/2ad945d9c0d201146a8ec86959424d6a.html