在特定范围内向 NSMutableAttributedString 添加属性

Adding attribute to NSMutableAttributedString on a specific range

我正在尝试为我的 NSMutableAttributedString 添加一个特定范围的背景属性,只要起始范围为 0,它就可以正常工作。每当我尝试将索引传递给函数时背景被添加到比预期更多的文本中。

这是演示该问题的视频。每当用户写错字母时,问题就会出现。

Video demonstration

代码:

var index = 0

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
    guard let char = string.cString(using: String.Encoding.utf8) else { return true }
    let isBackSpace = strcmp(char, "\b")
    if (isBackSpace == -92)
    {
        addBackground(color: .clear, from: index - 1, to: index)
        index -= 1
    }
    else
    {
        if charactersDoesMatch(char: string, i: index)
        {
            addBackground(color: .green, from: 0, to: index + 1)
        }
        else
        {
            //As you can see im trying to add it from the current index to the next one only.
            addBackground(color: .red, from: index, to: index + 1)
        }
        index += 1
    }
    return true
}

private func addBackground(color: UIColor, from: Int, to: Int)
{
    attributedText?.addAttribute(NSAttributedStringKey.backgroundColor, value: color, range: NSMakeRange(from, to))
    toTypelabel.attributedText = attributedText
}

我想我解决了你的问题

func NSMakeRange(_ loc: Int, 
           _ len: Int) -> NSRange

采用参数位置,第二个参数是长度,因此当输入错误值时,您输入 1 作为参数,这意味着只有一个字符应为红色

addBackground(color: .red, from: index, to: 1)

更多阅读苹果文档: NSMakeRange