代码改变世界

iOS UI基础 - 20 UITextField

  jiangys  阅读(334)  评论(0编辑  收藏  举报

 

复制代码
    //找到已经创建好的UITextField
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(50, 100, RFSCREEN_W - 100 , 45)];
    textField.leftImageName = @"login_user_icon"
    //设置边框样式
    textField.borderStyle = UITextBorderStyleNone;
    //通过layer设置圆角
    //textField.layer.cornerRadius = 10;
    textField.layer.borderColor = Color_White.CGColor;
    textField.layer.borderWidth = 1;
    // 设置字体颜色
    textField.textColor = Color_White;
    // 输入框中是否有个叉号,在什么时候显示,用于一次性删除输入框中的内容
    textField.clearButtonMode = UITextFieldViewModeAlways;
    //第一响应者,一个界面可能有多个可输入的控件,哪一个正在编辑哪一个就是第一响应者
    [textField becomeFirstResponder];
    // 设置左边图标
    UIImageView *leftImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"login_user_icon"]];
    leftImageView.frame = CGRectMake(0, 0, 50, 50);
    leftImageView.contentMode = UIViewContentModeCenter;
    textField.leftView = leftImageView;
    //设置左视图的显示模式
    textField.leftViewMode = UITextFieldViewModeAlways;
    // 设置键盘的样式
    textField.keyboardType = UIKeyboardTypeNumberPad;
    // 设置占位文字
    textField.placeholder = @"请输入用户名";
    // 设置占位文字的颜色
    [textField setValue:Color_White forKeyPath:@"placeholderLabel.textColor"];
    
    [self.view addSubview:textField];
复制代码

 限定只可以输入数字和6位长度

复制代码
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *text = [textField text];
    NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];
    string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
    if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) {
        return NO;
    }
    text = [text stringByReplacingCharactersInRange:range withString:string];
    text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    if ([text stringByReplacingOccurrencesOfString:@" " withString:@""].length >= 7) {
        return NO;
    }
    
    [textField setText:text];
    _confirmButton.enabled = text.length > 0 ? YES : NO;
    return NO;
}
复制代码

 

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端
点击右上角即可分享
微信分享提示