UITextField 光标、占位文字、输入监听及格式相关的知识点

  • 隐藏光标
self.codeTF.tintColor  = [UIColor clearColor];
  • 设置光标距左边的位置
 UIView *leftView = [[UIView alloc] init];
 leftView.frame = CGRectMake(0, 0, 10, 0);//宽度控制偏移位置
 textField.leftView = leftView;
 textField.leftViewMode = UITextFieldViewModeAlways;

同理修改左侧搜索默认的icon图片

    UIImageView *searchIcon = [[UIImageView alloc] init];
    searchIcon.image = [UIImage imageNamed:@"search_icon"];
    searchIcon.width = 30;
    searchIcon.height = 30;
    searchIcon.contentMode = UIViewContentModeCenter;
    textField.leftView = searchIcon;
    textField.leftViewMode = UITextFieldViewModeAlways;
  • 设置占位文字字体大小和颜色
[textFieldCheckInPerson setValue:[UIFont boldSystemFontOfSize:14] forKeyPath:@"_placeholderLabel.font"];
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
  • 键盘类型
UIKeyboardTypeDecimalPad //价格键盘
  • 清除按钮显示模式
textField.clearButtonMode = UITextFieldViewModeAlways;
typedef enum {
    UITextFieldViewModeNever,  重不出现
    UITextFieldViewModeWhileEditing, 编辑时出现
    UITextFieldViewModeUnlessEditing,  除了编辑外都出现
    UITextFieldViewModeAlways   一直出现
} UITextFieldViewMode;
显示、隐藏密码
- (IBAction)clickLookPswBtn:(UIButton *)sender {
    
    sender.selected = !sender.selected;
    self.pswTF.secureTextEntry = !self.pswTF.secureTextEntry;
}
  • 只能输入限定格式的内容

只能输入数字 #define LETTER @"0123456789"
只能输入纯大小写字母 #define LETTER @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
只能输入大小写字母和数字结合输入 #define LETTER @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:LETTER] invertedSet];
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    return [string isEqualToString:filtered];
}
  • 每四位加一个空格
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string isEqualToString:@""]) {// 四位加一个空格
        if ((textField.text.length - 2) % 5 == 0) {// 删除字符
            textField.text = [textField.text substringToIndex:textField.text.length - 1];
        }
        return YES;
    } else {
        if (textField.text.length % 5 == 0) {
            textField.text = [NSString stringWithFormat:@"%@ ", textField.text];
        }
    }
    return YES;
}
  • 监听textfield的输入
[textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

- (void)textFieldDidChange:(UITextField *)textField {}

参考资料:https://blog.csdn.net/tskyfree/article/details/8121915/
通过textfield自定义密码、验证码输入框:https://www.jianshu.com/p/23f7be3677be

你可能感兴趣的:(UITextField 光标、占位文字、输入监听及格式相关的知识点)