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

Swift中如何将NSMutableAttributedString赋值给UITextField实现超额字符标红

解决方案

UITextField 提供了attributedText属性专门用来接收富文本,你不需要通过普通的text属性赋值,直接把生成的NSMutableAttributedString赋值给这个属性即可。

现有代码还需要修正两处逻辑问题,避免崩溃和体验异常:

  • 你的getColoredText方法里的红色范围计算逻辑有问题,当文本长度超过限制时,超出部分的长度应该是文本总长度 - 允许长度,直接写string.length会触发数组越界崩溃;同时需要给限制内的字符显式设置默认颜色,避免继承异常样式。
  • 直接赋值attributedText会导致输入光标自动跳到文本末尾,影响连续输入体验,需要在赋值前后保存、恢复光标位置。

修改后的完整代码片段

1. checkRemainingChars 方法

func checkRemainingChars() {
    let currentLength = inputLimitField.text?.count ?? 0
    let remainingChars = allowedChars - currentLength
    characterCountLabel.textColor = .black
    inputLimitField.layer.borderColor = UIColor.systemGray6.cgColor
    
    if remainingChars < 0 {
        // 保存当前光标位置
        let selectedRange = inputLimitField.selectedTextRange
        // 生成富文本并赋值给attributedText属性
        let attributedStr = getColoredText(text: inputLimitField.text ?? "")
        inputLimitField.attributedText = attributedStr
        // 恢复光标到原有位置
        inputLimitField.selectedTextRange = selectedRange
        
        characterCountLabel.textColor = .red
        inputLimitField.layer.borderColor = UIColor.red.cgColor
        inputLimitField.layer.cornerRadius = 6.0
        inputLimitField.layer.borderWidth = 1.0
    } else {
        // 未超出限制时恢复普通文本样式
        inputLimitField.textColor = .black
    }
    characterCountLabel.text = ("\(remainingChars)/10")
}

2. getColoredText 方法

func getColoredText(text:String) -> NSMutableAttributedString{
    let string:NSMutableAttributedString = NSMutableAttributedString(string: text)
    // 给限制内的字符设置默认黑色
    string.addAttribute(.foregroundColor, value: UIColor.black, range: NSRange(location: 0, length: min(allowedChars, text.count)))
    // 仅当有超出字符时设置红色样式,避免越界
    let exceedLength = text.count - allowedChars
    if exceedLength > 0 {
        string.addAttribute(.foregroundColor, value: UIColor.red, range: NSRange(location: allowedChars, length: exceedLength))
    }
    return string
}

补充说明

如果你的UITextField有自定义的字体、段落对齐等默认样式,生成富文本时可以对应添加相关属性,避免富文本和普通文本样式不一致的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 19:06:01