0

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
}
2
  • Can you add the value of index when it starts adding wrong attribute? or any screenshot of the debugger when the wrong attribute is added? Commented Sep 25, 2018 at 10:17
  • The first time the error happens in the video the index is 9. So the red color should only be applied to 9 until 10. I'll try to make a video of the debugger. Commented Sep 25, 2018 at 10:21

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

I should learn to read up on documentation better, thanks a lot!
You're welcome, I also forget sometimes to read documentation, but we should read it because it will save us a lot of time later :)
Worst thing is I did read it, I just assumed it was a "from - to" range 😅

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.