I want to create a struct that returns Text. The text that it should return should detect whether a link is nested inside the text, and if so, open it when the text is tapped. I also want the specific link inside the text to be colored in blue while the rest of the text is default to the color Scheme. I got the detection working and the link to open on tap, but I can't get the link to be colored blue, and I am getting the error "Value of type 'URL' has no member 'startIndex'". I don't think the foreground modifier is allowed like this. I'd appreciate the help if anyone knows how to get this behavior to work
import Foundation
import UIKit
import SwiftUI
func coloredText(text: String) -> some View {
let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let matches = detector?.matches(in: text, options: [], range: NSRange(location: 0, length: text.utf16.count))
guard let url = matches?.first?.url else {
return Text(text)
}
return VStack {
Text(text)
.foregroundColor(.black)
.foregroundColor(.blue, range: NSRange(url.startIndex..<url.endIndex, in: text))
.onTapGesture {
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url)
}
}
}
}