LoginSignup
0
0

[Swift]safariを起動してリンクを開くコードの作成

Last updated at Posted at 2023-08-10

テキストをリンクとして実装するためには、UITextViewを使用することができます。以下に、テキストをリンクとして表示し、タップすると https://www.google.com にアクセスするコード例を示します。

  1. まず、Storyboard上にUITextViewを配置します。
  2. UITextViewを配置したら、そのUITextViewをViewControllerのコードと接続します
  3. 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/にアクセスできるようになります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0