gpt4 book ai didi

swift - Textview 替换字符不起作用

转载 作者:行者123 更新时间:2023-11-30 10:49:53 25 4
gpt4 key购买 nike

我正在尝试在 TextView 中添加带有 attributeText 的粗体字体。这种字体将在某些按钮操作后应用,我的问题是每当我添加粗体字体时。它添加粗体字体并重复单词。在附图中,应在“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
}

enter image description here

最佳答案

我不知道为什么您的文字会重复。我猜想这与您替换范围中的字符有关,而该函数也替换范围中的字符(您替换范围两次,因此是双文本)。

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

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

关于swift - Textview 替换字符不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54828299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com