English 中文(简体)
Swift UI coloring url links inside of text blue while rest of text black
原标题:

Hello I want to create a struct that returns Text, the text that it should return should detect wether 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. Id 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)
                }
            }
        
    }
}
问题回答

暂无回答




相关问题
SwiftUI: How do I position a button x points above a sheet?

I am trying to recreate a Maps-style UI with a persistent bottom sheet and controls fixed above. Apple Maps UI with controls above ☝️ Example here, the "Look Around" binoculars button and ...

BraintreeDropIn deprecated functions error

I m getting this error on the latest release of BraintreeDropIn, I really don t get it since based on the patch notes, this should ve been addressed already, I have already tried cleaning derived data,...

how to limit zoom level in map swift ui?

how to limit zoom level in map swift ui i have map and need to make zoom level limited Map(coordinateRegion: $region,annotationItems: viewModel.nearbyGyms) { item in ...

UIImageView - How to get the file name of the image assigned?

Is it possible to read the name of an UIImageView s UIImage that s presently stored in the UIImageView? I was hoping you could do something kind of like this, but haven t figured it out. NSString *...

热门标签