【问题标题】:Textview replacing characters not workingTextview替换字符不起作用
【发布时间】:2019-02-22 13:35:18
【问题描述】:

我正在尝试在我的文本视图中添加带有属性文本的粗体字体。此字体将在某些按钮操作后应用,我的问题是每当我添加粗体字体时。它正在添加粗体并重复单词。在附图中,应在“hello”一词之后添加粗体字。所以它显示为 这是粗体

这是我尝试过的:

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

    if boldFont {
        let boldStyle = NSAttributedString(string: text, attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 20)])
        textView.textStorage.replaceCharacters(in: range, with: boldStyle)
    }
    return true
}

【问题讨论】:

    标签: swift textview nsattributedstring nsrange


    【解决方案1】:

    我不知道为什么你的文字重复。我会 它与您替换一个范围内的字符有关,而该函数还替换一个范围内的字符(您要替换一个范围两次,因此是双重文本)。

    但是,我不会将 shouldChangeTextIn 方法用于您要执行的操作。为什么不直接替换按钮点击时的 textView.text 呢??

    buttonAction() {
       textView.attributedText = // bolded text
    }
    

    【讨论】:

    • 感谢您的回复。每当我尝试您的建议时,textview 中的所有文本都会被删除。
    猜你喜欢
    • 2017-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    • 2016-02-15
    • 2016-10-05
    • 2012-07-08
    • 2011-08-12
    相关资源
    最近更新 更多