I'm currently working on a chat app and i managed to make so that if a message contains a link, that link would get underlined.
The code i'm using:
func attribute(string: String) -> Text {
guard let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
else {
return Text(string)
}
let stringRange = NSRange(location: 0, length: string.count)
let matches = detector.matches(
in: string,
options: [],
range: stringRange
)
let attributedString = NSMutableAttributedString(string: string)
for match in matches {
attributedString.addAttribute(.underlineStyle, value: NSUnderlineStyle.single, range: match.range)
}
var text = Text("")
attributedString.enumerateAttributes(in: stringRange, options: []) { attrs, range, _ in
var t = Text(attributedString.attributedSubstring(from: range).string)
if attrs[.underlineStyle] != nil {
t = t
.foregroundColor(Color.white)
.underline()
} else {
t = t
.foregroundColor(Color.white)
}
text = text + t
}
return text
}
My next goal is to make that link clickable. I tried applying onTapGesture modifiers, but that causes an error:
Cannot assign value of type 'some View' to type 'Text'
I've tried several topics here, but they have a different approach since they set a static string, these messages are being fetched from firebase.
Thank you for all of the possible suggestions and help!