gpt4 book ai didi

swift - 当单词以 @ 开头时,通过键盘输入更改 TextView 中的单词格式

转载 作者:行者123 更新时间:2023-11-30 12:01:00 26 4
gpt4 key购买 nike

我正在尝试在 uitextfield 中格式化键盘输入的单词,

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


let words = textView.text.components(separatedBy: " ")
for word in words{
if word.hasPrefix("@"){
let attributes = [NSForegroundColorAttributeName: UIColor.blue, NSFontAttributeName: self.textView.font!] as [String : Any]
let attributedString = NSMutableAttributedString(string: word, attributes: attributes)
self.textView.textStorage.insert(attributedString, at: range.location)
let cursor = NSRange(location: self.textView.selectedRange.location+1, length: 0) //textView.text.range(of: word)
textView.selectedRange = cursor
return true
}
}

return true
}

enter image description here

任何想法如何完成它预期结果应该是@yoel l

最佳答案

这将检查每个空格后的最后一个单词是否包含“@”:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == " ",let lastWord = textView.text.components(separatedBy: " ").last, lastWord.contains("@"), let lastWordRange = (textView.text as? NSString)?.range(of: lastWord){
let attributes = [NSForegroundColorAttributeName: UIColor.blue, NSFontAttributeName: self.textView.font!] as [String : Any]
let attributedString = NSMutableAttributedString(string: lastWord, attributes: attributes)
textView.textStorage.replaceCharacters(in:lastWordRange, with:attributedString)
}
return true
}

关于swift - 当单词以 @ 开头时,通过键盘输入更改 TextView 中的单词格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47231134/

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