【问题标题】:Cannot convert value of type 'Range<String.Index>' to expected argument type 'UITextRange'无法将“Range<String.Index>”类型的值转换为预期的参数类型“UITextRange”
【发布时间】:2017-09-25 12:56:14
【问题描述】:

如何根据字符串创建范围。使用下面的代码,我收到错误“无法将'Range'类型的值转换为预期的参数类型'UITextRange'”。仅供参考 print(firstString[range]) 成功输出“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()
  }
}

【问题讨论】:

  • 试试textView.text.replace(range, withText: secondString)

标签: swift string uitextview


【解决方案1】:

您的代码中有两个问题。首先,您需要在 textView 文本属性中应用您的方法。第二个问题是您使用了错误的方法,要替换字符串的范围,您需要使用 replaceSubrange 方法。所以你的代码应该是这样的:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多