gpt4 book ai didi

swift - 在 TextView 中解析主题标签

转载 作者:搜寻专家 更新时间:2023-11-01 07:16:49 24 4
gpt4 key购买 nike

我在 TextView 上设置文本,然后调用 UITextView 扩展的这个方法,以便从主题标签和提及的单词中创建链接 (Swift 3)

extension UITextView {
func resolveHashTags(font: UIFont = UIFont.systemFont(ofSize: 17.0)){
if let text = self.text {

let words:[String] = text.components(separatedBy: " ")

let attrs = [ NSFontAttributeName : font ]
let attrString = NSMutableAttributedString(string: text, attributes:attrs)
for word in words {
if (word.characters.count > 1 && ((word.hasPrefix("#") && word[1] != "#") || (word.hasPrefix("@") && word[1] != "@"))) {

let matchRange = text.range(of: word)
let newWord = String(word.characters.dropFirst())

if let matchRange = matchRange {

attrString.addAttribute(NSLinkAttributeName, value: "\(word.hasPrefix("#") ? "hashtag:" : "mention:")\(newWord)", range: text.NSRangeFromRange(range: matchRange))
}
}
}

self.attributedText = attrString
}
}
}

我的问题很简单。我无法为类似 "helloworld#hello" 的内容创建链接,因为我的单词没有前缀 "#"

我无法弄清楚的另一种情况是,当用户将多个主题标签放在一起时,例如 “hello world,你好吗?#success#moments#connect”,因为这都将被视为 1当它应该是 3 个不同的链接时,带有当前逻辑的标签。

我该如何纠正?谢谢

最佳答案

func resolveHashTags(text : String) -> NSAttributedString{
var length : Int = 0
let text:String = text
let words:[String] = text.separate(withChar: " ")
let hashtagWords = words.flatMap({$0.separate(withChar: "#")})
let attrs = [NSFontAttributeName : UIFont.systemFont(ofSize: 17.0)]
let attrString = NSMutableAttributedString(string: text, attributes:attrs)
for word in hashtagWords {
if word.hasPrefix("#") {
let matchRange:NSRange = NSMakeRange(length, word.characters.count)
let stringifiedWord:String = word

attrString.addAttribute(NSLinkAttributeName, value: "hash:\(stringifiedWord)", range: matchRange)
}
length += word.characters.count
}
return attrString
}

为了分隔单词,我使用了字符串扩展

extension String {
public func separate(withChar char : String) -> [String]{
var word : String = ""
var words : [String] = [String]()
for chararacter in self.characters {
if String(chararacter) == char && word != "" {
words.append(word)
word = char
}else {
word += String(chararacter)
}
}
words.append(word)
return words
}

}

func textViewDidChange(_ textView: UITextView) {
textView.attributedText = resolveHashTags(text: textView.text)
textView.linkTextAttributes = [NSForegroundColorAttributeName : UIColor.red]
}

希望这就是您要找的。告诉我它是否适合您。

关于swift - 在 TextView 中解析主题标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41750288/

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