Created
May 12, 2022 10:50
-
-
Save ole/8d1ef1cab4bbd387c3bdc8c69e29eae3 to your computer and use it in GitHub Desktop.
Add links in SwiftUI Text views via a custom string interpolation.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
extension LocalizedStringKey.StringInterpolation { | |
/// String interpolation support for links in Text. | |
/// | |
/// Usage: | |
/// | |
/// let url: URL = … | |
/// Text("\("Link title", url: url)") | |
mutating func appendInterpolation(_ linkTitle: String, link url: URL) { | |
var linkString = AttributedString(linkTitle) | |
linkString.link = url | |
self.appendInterpolation(linkString) | |
} | |
/// String interpolation support for links in Text. | |
/// | |
/// Usage: | |
/// | |
/// Text("\("Link title", url: "https://example.com")") | |
mutating func appendInterpolation(_ linkTitle: String, link urlString: String) { | |
self.appendInterpolation(linkTitle, link: URL(string: urlString)!) | |
} | |
} | |
// MARK: - Usage example | |
struct ContentView: View { | |
var body: some View { | |
VStack(spacing: 20) { | |
// Link with custom string interpolation. | |
Text("This is a \("custom string interpolation link", link: "https://example.com").") | |
// Markdown works too. | |
Text("This is a [Markdown link](https://example.com).") | |
} | |
.padding() | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
ContentView() | |
} | |
} |
Author
ole
commented
May 12, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment