在特定范围内将属性添加到NSMutableAttributedString

时间:2018-09-25 10:05:09

标签: ios swift nsattributedstring nsrange

我正在尝试将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
}

1 个答案:

答案 0 :(得分:1)

我想我已经解决了您的问题

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

获取参数位置,第二个为长度,因此当输入错误的值时,请输入1作为参数,这意味着仅一个字符应被涂成红色

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

有关Apple文档的更多信息,请参阅: NSMakeRange