Wednesday, February 14, 2024
HomeiOS Developmentios - Allow menu when lengthy urgent on URL

ios – Allow menu when lengthy urgent on URL


Possibly you would attempt the next. I’ve considered a tokenizer that splits each URL within the string you move to the Textual content:

struct ContentView: View {
    let textWithUrls = "Go to https://stackoverflow1.com and https://stackoverflow2.com https://stackoverflow3.com - https://stackoverflow2.com https://stackoverflow4.com"

    var physique: some View {
        VStack {
            Textual content(textWithUrls)
                .padding()
                .contextMenu(menuItems: {
                    // Loop by URL strings
                    ForEach(getUrls(from: textWithUrls), id: .self) { url in
                        // A View of your chosing right here. I've used Button.
                        Button(motion: {
                            if let url = URL(string: url) {
                                UIApplication.shared.open(url)
                            }
                        }) {
                            Textual content(url)
                                .padding()
                        }
                    }
                })

            
        }
    }

    // Operate to extract URLs from the textual content utilizing common expression
    non-public func getUrls(from textual content: String) -> [String] {
        do {
            let detector = attempt NSDataDetector(sorts: NSTextCheckingResult.CheckingType.hyperlink.rawValue)
            let matches = detector.matches(in: textual content, choices: [], vary: NSRange(location: 0, size: textual content.utf16.depend))
            return matches.compactMap { $0.url?.absoluteString }
        } catch {
            print("Error: (error)")
            return []
        }
    }
}

I’ve tried separating the string utilizing areas, phrases and dashes and it has at all times labored. The getUrls perform makes use of a daily expression to dectect URLs and returns them as an array of String.

This is the outcome:

Context menu tokenized URLs

Let me know in the event you like this resolution!



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments