You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS开发:为何清空文本后UITextField的textColor从红变蓝?

UITextField清空文本后颜色变为蓝色的原因分析

你设置UITextField初始文本为红色,但清空后再输入时颜色变为蓝色,预期所有状态下文本都保持红色,你的实现代码如下:

@interface ViewController ()

@property (nonatomic, strong) UITextField *textField;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(100, 100, 100, 30)];
    self.textField.textColor = UIColor.blueColor;
    self.textField.text = @"hello world";
    NSAttributedString *attributedText = self.textField.attributedText;
    NSMutableAttributedString *mAttributedText = attributedText.mutableCopy;
    [attributedText enumerateAttribute:NSForegroundColorAttributeName inRange:NSMakeRange(0, attributedText.length) options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(id  _Nullable value, NSRange range, BOOL * _Nonnull stop) {
        [mAttributedText addAttribute:NSForegroundColorAttributeName value:UIColor.redColor range:range];
    }];
    self.textField.attributedText = mAttributedText;
    
    [self.view addSubview:self.textField];
}

@end

问题原因

  • 你先设置了self.textField.textColor = UIColor.blueColor;,这个属性是UITextField的默认文本颜色。当文本被清空后,原有富文本的颜色属性会被移除,后续输入新内容时,UITextField会自动使用这个默认的textColor值,也就是蓝色。
  • 通过attributedText设置的红色仅作用于当前已存在的文本内容,一旦文本被清空,这些富文本属性也会随之消失,无法影响后续输入的文本样式。

解决方案

如果要让所有状态下的文本(包括清空后重新输入的内容)都保持红色,推荐两种处理方式:

  1. 直接设置默认文本颜色为红色,无需额外处理富文本:
self.textField = [[UITextField alloc] initWithFrame:CGRectMake(100, 100, 100, 30)];
self.textField.textColor = UIColor.redColor;
self.textField.text = @"hello world";
[self.view addSubview:self.textField];
  1. 若必须使用富文本,同时确保后续输入的文本也保持红色,可以设置typingAttributes属性,指定输入时的文本样式:
// 在viewDidLoad中添加
self.textField.typingAttributes = @{NSForegroundColorAttributeName: UIColor.redColor};

内容的提问来源于stack exchange,提问作者ios learner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 22:22:26