iOS初体验-UITextField 输入框

UITextField 输入框:ios提供的一种用来显示文字和编辑文字的空间
  //1.创建对象
    UITextField *tf = [[UITextField alloc]initWithFrame:CGRectMake(100, 100, 150, 40)];
    //2.配置属性
    tf.tag = 110;
    tf.backgroundColor = [UIColor lightGrayColor];
    //2.1显示文字
    tf.text = @"123";
    //2.2设置默认提示文字
    tf.placeholder = @"请输入用户名";
    //2.3输入文字的yanse
    tf.textColor = [UIColor orangeColor];
    //2.4对齐方式
    tf.textAlignment = NSTextAlignmentCenter;
    //2.5安全模式
        tf.secureTextEntry= YES;
    //2.6文字字体样式大小;
    tf.font =[UIFont systemFontOfSize:20];
    //2.7设置清除按钮:
    tf.clearButtonMode =UITextFieldViewModeAlways;
    //2.8当第一次选中输入框时,是否清空输入框的内容
    tf.clearsOnBeginEditing = YES;
    //2.9设置输入框的边界样式
    tf.borderStyle = UITextBorderStyleLine;
//    tf.borderStyle = UITextBorderStyleBezel;
    //2.10设置是否可以编辑
//    tf.enabled = NO;//默认YES 可编辑;
//    tf.userInteractionEnabled = NO;//关闭用户交互
    //2.11设置键盘样式
    tf.keyboardType =  UIKeyboardTypeDefault;
    //2.12设置键盘外观
    tf.keyboardAppearance =UIKeyboardAppearanceDark;
    //2.13设置return键的样式
    tf.returnKeyType = UIReturnKeyGo;
    //2.14 设置左边的视图
    UILabel *left = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, 50, 20)];
    left.text =@"账号:";
//    left.backgroundColor =[UIColor yellowColor];
    tf.leftView = left;
    tf.leftViewMode = UITextFieldViewModeAlways;
    //2.15 设置自定义键盘
//    tf.inputView = customInput;
    
    //2.16 自定义键盘辅助视图
//    tf.inputAccessoryView = accrossView;





//点击空白区域  回收键盘
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
      NSLog(@"%s",__FUNCTION__);
//    [self.window endEditing:YES];
    [[self.window viewWithTag:110] resignFirstResponder];
}
//****************协议方法****************
//是否支持编辑
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    NSLog(@"%s",__FUNCTION__);
    return YES;//YES可以编辑   NO不可以编辑
}
//已经进入编辑状态.
- (void)textFieldDidBeginEditing:(UITextField *)textField{
       NSLog(@"%s",__FUNCTION__);
}
//是否可以取消编辑状态
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
       NSLog(@"%s",__FUNCTION__);
    return YES;
}
//已经取消编辑状态 结束编辑
- (void)textFieldDidEndEditing:(UITextField *)textField{
       NSLog(@"%s",__FUNCTION__);
}
//当输入框内容发生变化时; 能够及时的获取输入的最新内容
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
       NSLog(@"%s",__FUNCTION__);
    
    NSLog(@"%@",string);
    return YES;
}
//是否可以清空内容
- (BOOL)textFieldShouldClear:(UITextField *)textField{
       NSLog(@"%s",__FUNCTION__);
    return YES;
}
//点击return键时触发;常用于回收键盘.
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
       NSLog(@"%s",__FUNCTION__);
    [textField resignFirstResponder];
    return YES;
}
原文地址:https://www.cnblogs.com/sunmair/p/5905832.html