Created
April 30, 2020 10:33
-
-
Save takoikatakotako/e27013d8f4e500b8eb35978a225927b9 to your computer and use it in GitHub Desktop.
SwiftUI で文字列中にタップ可能なリンクを追加する
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 | |
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() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
参考: https://qiita.com/shtnkgm/items/3c8b6b794219fbf087ba