Search code examples
iosswiftnsattributedstringnsrange

Adding attribute to NSMutableAttributedString on a specific range


I'm trying to add a background attribute to my NSMutableAttributedString for a specific range, which is working fine as long as the start range is 0. Whenever I try to pass a index to the function the background gets added to a lot more text than intended.

Here is a video demonstrating the issue. Whenever the user writes a wrong letter the issue appears.

Video demonstration

Code:

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
}

Solution

  • I think I figured out your problem

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

    Takes parameters location and second one is length, so when entering wrong value you enter 1 as parameter meaning only one character should be colored in red

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

    For more read apple documentation: NSMakeRange