2
votes

How to create range based on a string. With below code, I'm getting the error "Cannot convert the value of type 'Range' to expected argument type 'UITextRange'". FYI print(firstString[range]) successfully output "xxx".

class ViewController: UIViewController {
  @IBOutlet weak var textView: UITextView!
  let firstString: String = "xxx"
  let secondString: String = "yyy"

  override func viewDidLoad() {
    super.viewDidLoad()
    textView.text = firstString
  }

  func replace() {
    var finalString: String?
    let range = firstString.startIndex..<firstString.endIndex
    print(firstString[range])
    textView.replace(range, withText: secondString)
  }

  @IBAction func replaceButton(_ sender: Any) {
    replace()
  }
}
1
try it textView.text.replace(range, withText: secondString)Salman Ghumsani

1 Answers

0
votes

You have two problems in your code. First you need to apply your method in your textView text property. Second problem is that you are using the wrong method, to replace a range of your string you need to use replaceSubrange method. So your code should look something like this:

textView.text.replaceSubrange(range, with: secondString)