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设置的红色仅作用于当前已存在的文本内容,一旦文本被清空,这些富文本属性也会随之消失,无法影响后续输入的文本样式。
解决方案
如果要让所有状态下的文本(包括清空后重新输入的内容)都保持红色,推荐两种处理方式:
- 直接设置默认文本颜色为红色,无需额外处理富文本:
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];
- 若必须使用富文本,同时确保后续输入的文本也保持红色,可以设置
typingAttributes属性,指定输入时的文本样式:
// 在viewDidLoad中添加 self.textField.typingAttributes = @{NSForegroundColorAttributeName: UIColor.redColor};
内容的提问来源于stack exchange,提问作者ios learner
相关产品推荐
相关产品推荐

