iOS 自定义TextField字体颜色和显示位置,限制字体输入个数

本文介绍如何通过自定义UITextField来调整字体颜色、大小及位置,并提供限制输入长度的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目中 肯定需要自定义TextField 来改变默认的字体颜色大小和显示位置

不废话直接上代码

设置字体颜色和大小

 [self.tfUserName setValue:[UIFont systemFontOfSize:font(13)] forKeyPath:@"_placeholderLabel.font"];

  [self.tfUserName setValue:RGBColor(208,206,206) forKeyPath:@"_placeholderLabel.textColor"];

设置字体显示位置和placeholder位置 必须继承UiTextField实现自定义UiTextField

//控制placeHolder的位置
-(CGRect)placeholderRectForBounds:(CGRect)bounds
{
    CGRect inset=CGRectMake(34, 1, 44, 14);
    return inset;
}

//控制编辑文本的位置
-(CGRect)editingRectForBounds:(CGRect)bounds

{

    CGRect inset = CGRectMake(bounds.origin.x +34, bounds.origin.y+1, bounds.size.width -10, bounds.size.height);

    return inset; 
}

//控制显示文本的位置
-(CGRect)textRectForBounds:(CGRect)bounds
{
    CGRect inset = CGRectMake(bounds.origin.x +34, bounds.origin.y+1, bounds.size.width -10, bounds.size.height);
    return inset;
}

这里写图片描述

因为前面图片是放在uitextfield 上面 所以我把显示的x坐标 移动的比较多 没有图片的话 5就差不多了

限制textfield输入的长度

[self.loginView.tfUserName addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
//电话号码11位号码限制
- (void)textFieldDidChange:(UITextField *)textField
{
    if (textField == self.loginView.tfUserName) {
        if (textField.text.length >11) {
            textField.text = [textField.text substringToIndex:11];
        }
    }
}

好了,搞定了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值