Advertisement
Milotronik

TextWithLinks

Jun 28th, 2024
934
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 2.08 KB | None | 0 0
  1. import SwiftUI
  2. import UIKit
  3.  
  4. struct ContentView: View {
  5.     var body: some View {
  6.         VStack {
  7.             Text("it works")
  8.            
  9.             LinkedTextView(
  10.                 text: "I have a Link and another Link2 ahds jadjsah dhjasjhdsa j jdas d asj dsjhd jadhjadshjd ",
  11.                 links: ["Link": "https://google.gl", "Link2": "https://bing.com"],
  12.                 onLinkTapped: { url in
  13.                     print("\(url.absoluteString) tapped")
  14.                 }
  15.             )
  16.             Text("it works")
  17.         }
  18.     }
  19. }
  20.  
  21. struct LinkedTextView: View {
  22.     // Your text from the server
  23.     let text: String
  24.    
  25.     // Your dictionary with links
  26.     let links: [String: String]
  27.    
  28.     let onLinkTapped: (_ url: URL) -> Void
  29.    
  30.     @Environment(\.openURL) private var openURL
  31.    
  32.     var body: some View {
  33.         Text(makeAttributedString())
  34.             .font(.title)
  35.             .environment(\.openURL, OpenURLAction(handler: handleURL))
  36.     }
  37.    
  38.     func handleURL(_ url: URL) -> OpenURLAction.Result {
  39.         // - Use .handled if you've performed a custom action
  40.         // - Use .discarded if you weren't able to handle the link
  41.         if UIApplication.shared.canOpenURL(url) {
  42.             onLinkTapped(url)
  43.             return .handled
  44.         }
  45.         return .discarded
  46.     }
  47.    
  48.     func makeAttributedString() -> AttributedString {
  49.         var attributedString = AttributedString(text)
  50.         // Iterate through the dictionary and add link attributes
  51.         for (key, value) in links {
  52.             if let range = attributedString.range(of: key) {
  53.                 // Define the URL attribute
  54.                 attributedString[range].link = URL(string: value)
  55.                
  56.                 // Apply different text style for the links
  57.                 attributedString[range].foregroundColor = .blue
  58.                 attributedString[range].underlineStyle = .single
  59.                 attributedString[range].font = .caption
  60.             }
  61.         }
  62.        
  63.         return attributedString
  64.     }
  65. }
  66.  
  67. #Preview {
  68.     ContentView()
  69. }
  70.  
Tags: ios
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement