Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import SwiftUI
- import UIKit
- struct ContentView: View {
- var body: some View {
- VStack {
- Text("it works")
- LinkedTextView(
- text: "I have a Link and another Link2 ahds jadjsah dhjasjhdsa j jdas d asj dsjhd jadhjadshjd ",
- links: ["Link": "https://google.gl", "Link2": "https://bing.com"],
- onLinkTapped: { url in
- print("\(url.absoluteString) tapped")
- }
- )
- Text("it works")
- }
- }
- }
- struct LinkedTextView: View {
- // Your text from the server
- let text: String
- // Your dictionary with links
- let links: [String: String]
- let onLinkTapped: (_ url: URL) -> Void
- @Environment(\.openURL) private var openURL
- var body: some View {
- Text(makeAttributedString())
- .font(.title)
- .environment(\.openURL, OpenURLAction(handler: handleURL))
- }
- func handleURL(_ url: URL) -> OpenURLAction.Result {
- // - Use .handled if you've performed a custom action
- // - Use .discarded if you weren't able to handle the link
- if UIApplication.shared.canOpenURL(url) {
- onLinkTapped(url)
- return .handled
- }
- return .discarded
- }
- func makeAttributedString() -> AttributedString {
- var attributedString = AttributedString(text)
- // Iterate through the dictionary and add link attributes
- for (key, value) in links {
- if let range = attributedString.range(of: key) {
- // Define the URL attribute
- attributedString[range].link = URL(string: value)
- // Apply different text style for the links
- attributedString[range].foregroundColor = .blue
- attributedString[range].underlineStyle = .single
- attributedString[range].font = .caption
- }
- }
- return attributedString
- }
- }
- #Preview {
- ContentView()
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement