Skip to content

Instantly share code, notes, and snippets.

@takoikatakotako
Created April 30, 2020 10:33
Show Gist options
  • Save takoikatakotako/e27013d8f4e500b8eb35978a225927b9 to your computer and use it in GitHub Desktop.
Save takoikatakotako/e27013d8f4e500b8eb35978a225927b9 to your computer and use it in GitHub Desktop.
SwiftUI で文字列中にタップ可能なリンクを追加する
import SwiftUI
struct ContentView: View {
var body: some View {
AttributedText(getAttributeString())
}
func getAttributeString() -> NSAttributedString {
let baseString = """
This is a sentence that includes a link to the settings app.
This is a sentence that includes a link to the Google search.
"""
let attributedString = NSMutableAttributedString(string: baseString)
attributedString.addAttribute(.link,
value: UIApplication.openSettingsURLString,
range: NSString(string: baseString).range(of: "the settings app"))
attributedString.addAttribute(.link,
value: "https://www.google.co.jp/",
range: NSString(string: baseString).range(of: "the Google search"))
return attributedString
}
}
struct AttributedText: UIViewRepresentable {
var attributedText: NSAttributedString
init(_ attributedText: NSAttributedString) {
self.attributedText = attributedText
}
func makeUIView(context: Context) -> UITextView {
let textView = UITextView()
textView.isEditable = false
textView.isSelectable = true
return textView
}
func updateUIView(_ textView: UITextView, context: Context) {
textView.attributedText = attributedText
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
@takoikatakotako
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment