【问题标题】:Replace selected string in TextView替换 TextView 中的选定字符串
【发布时间】:2022-01-05 01:59:26
【问题描述】:

在文本视图中,用户选择文本,然后单击按钮。如何用新的文本替换选定的文本,当用户按下按钮时,它将代替选定的文本?

我尝试使用下一个代码来获取选定的文本:

guard let range = textViewText.selectedTextRange else {return}

但是如何通过单击按钮将其替换为新字符串?

【问题讨论】:

    标签: swift textview


    【解决方案1】:

    用新文本更改范围内的文本:

    textView.textStorage.replaceCharacters(in: range, with: string)
    

    您还需要将范围(作为 selectedRange)保存在类的属性中,以便在 IBAction 中访问它。

    【讨论】:

    • 我尝试使用 textViewText.selectedTextRange else {return} 保存范围,但我无法将类型“UITextRange”的值转换为预期的参数类型“NSRange”(又名“_NSRange”)
    • 你能显示你得到错误的代码行吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    • 2012-09-29
    • 2021-06-21
    • 2020-10-04
    相关资源
    最近更新 更多