Search code examples
iosuitextviewnsrange

Restrict edit in range in UITextView


I have an array of NSRanges, I want these ranges to be immutable/readonly in my UITextView. But I am not quite sure on how I should restrict the edit to the ranges which is not present in the array.

I have tried the following.

 func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {

          for range in immutableRange {

            if changeRange.location == range.location {
                return false
            }
        }
        return true
    }

But this is not working as expected. How can I sort this out, so the user only is allowed to change the text which is in the ranges not included in the array?

EDIT:

I also tried using the following:

NSLocationInRange(immutableRange.location, changeRange) && NSLocationInRange(NSMaxRange(immutableRange), changeRange)

to check whether the changeRange contained the immutableRange, but that didn't work as expected either.

I have the following types of string : "There is ______ red flowers, ______ green flowers and ______ yellow flowers", where everything else than "____" is the immutableRanges.


Solution

  • Your check for each range isn't correct. Instead of seeing if each range is equal, you need to check if each range intersects:

    for range in immutableRange {
        var overlap = NSIntersectionRange(changeRange, range)
        if overlap.length != 0 {
            return false // the ranges overlap
        }
    }
    

    I'm not fluent in Swift. The above code may have syntax errors. Fix as needed.

    Also, this is only a partial fix for what you are trying to achieve. This will protect the read-only parts of the original string but you need a lot more code to properly allow a user to type in the unprotected areas without messing everything else up.