Home>

I want to replace the character string in the selected range of TextView with the specified character string
For example, I would like to know how to replace the following character string with the specified character string when the following character string exists in the text field and the range from 1 to 4 (XXX part) is selected.

"AXXXEFG"

Since the first index and the last index of the selection range could be obtained by textView.selectedRange.location/length, I tried to specify the range with the following method and replace it, but an error occurs.

textView.text.replaceSubrange (textView.text.index (textView.text.startIndex,
                              offsetBy: textView.selectedRange.length),
                              with: "BCD") // I haven't considered whether this method is destructive for the time being.
Error message
Instance method'replaceSubrange (_: with :)' requires that'String.Index' conform to'RangeExpression'

It is uncertain what kind of character string is contained in textView.

  • Answer # 1

    replaceSubrange (_: with :)The first argument ofRangeBecause it takesNSRangeToRangeI think it would be good to convert it to.

          if let range = Range (textView.selectedRange, in: textView.text) {
                textView.text.replaceSubrange (range, with: "###")
            }

    index (_: offsetBy :)The return value ofString.IndexSo it is requiredRangeIsn't it the cause of the error that is different from?

    index (_: offsetBy :)
    Returns an index that is the specified distance from the given index.

Related articles