テキストをリンクとして実装するためには、UITextViewを使用することができます。以下に、テキストをリンクとして表示し、タップすると https://www.google.com にアクセスするコード例を示します。
- まず、Storyboard上にUITextViewを配置します。
- UITextViewを配置したら、そのUITextViewをViewControllerのコードと接続します
- ViewControllerのコードに、以下のコードを追加します。
import UIKit
import SafariServices
class ViewController: UIViewController, UITextViewDelegate {
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Set the text and link attributes for the UITextView
let attributedText = NSMutableAttributedString(string: "Visit Google")
attributedText.addAttribute(.link, value: "https://www.google.com/", range: NSRange(location: 0, length: attributedText.length))
textView.delegate = self
textView.attributedText = attributedText
textView.isUserInteractionEnabled = true
textView.isEditable = false
}
// UITextViewDelegate method to handle link tap
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
let safariViewController = SFSafariViewController(url: URL)
present(safariViewController, animated: true, completion: nil)
return false
}
}
このコードでは、UITextViewを使用してテキストを表示し、そのテキストをリンクとして扱うためにattributedTextを使用してリンク属性を設定しています。shouldInteractWithメソッドは、リンクがタップされた際に呼ばれ、SFSafariViewControllerを使用してリンク先にアクセスします。
これにより、テキストをリンクとして表示し、タップするとSFSafariViewControllerを使用してhttps://www.google.com/にアクセスできるようになります。