I have posts on my app where users can tag other users, the expectation is that these tags should be tappable and trigger a function when tapped.
For example the post: "hello @someUser and @otherUser" the @someUser and @otherUser should be tappable.
This is the code I've tried, but it's only showing text with tagged users, from the example above it is only displaying: "@someUser @otherUser" without the rest of the text. The tapping implementation does work but no other text is displayed, and I don't think an HStack is ideal here
Is there a better way to handle this in SwiftUI?
@ViewBuilder
func bodyTextView(text: String) -> some View {
HStack {
ForEach(attributedText(text: text), id: \.self) { text in
if text.hasPrefix("@") {
Text(text)
.onTapGesture {
print("TAP: \(text)")
}
} else {
Text(text)
}
}
}
}
func attributedText(text: String) -> [String] {
let inputString = text
let regexPattern = "@\\w+"
guard let regex = try? NSRegularExpression(pattern: regexPattern) else {
return [inputString]
}
let range = NSRange(inputString.startIndex..<inputString.endIndex, in: inputString)
let matches = regex.matches(in: inputString, range: range)
var substrings: [String] = []
for match in matches {
if let swiftRange = Range(match.range, in: inputString) {
let substring = String(inputString[swiftRange])
substrings.append(substring)
}
}
return substrings
}