2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Swift(Xcode)のUILabelを文字をURLの部分だけリンク化

Posted at

1.はじめに
私は現在、独学でSwift(主にstoryboard)を勉強し、IDNectというアプリを開発しています。また、自社開発会社にてアルバイトとして働かせていただいています。

AIでも回答できると機能紹介しかできないと思いますが、
時間があるときにアプリの改修の際に使用したコードをQiitaに公開したいと思います。

以下のコードにすることでURLの部分だけ文字の色を変えて、タップすることでWebサイトに飛ぶことができます。

ここでは私が開発したIDNectというアプリのWebサイトを表示するようにしています。

2.実際のコード

Viewcontroller
import UIKit

class ViewController: UIViewController {
    @IBOutlet var label: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(labelTapped))
        label.isUserInteractionEnabled = true
        label.addGestureRecognizer(tapGesture)
        toLink()
    }

    func toLink() {
        let labelText = "こちらのリンクを確認してください: https://IDNect.com"
        let types: NSTextCheckingResult.CheckingType = .link
        let detector = try? NSDataDetector(types: types.rawValue)
        let matches = detector?.matches(in: labelText, options: [], range: NSRange(location: 0, length: labelText.utf16.count))

        let attributedString = NSMutableAttributedString(string: labelText)

        matches?.forEach { match in
            attributedString.addAttribute(.foregroundColor, value: UIColor.blue, range: match.range)
        }

        label.attributedText = attributedString
    }

    @objc func labelTapped() {
        guard let labelText = label.attributedText?.string else { return }
        let types: NSTextCheckingResult.CheckingType = .link
        let detector = try? NSDataDetector(types: types.rawValue)
        let matches = detector?.matches(in: labelText, options: [], range: NSRange(location: 0, length: labelText.utf16.count))

        if let match = matches?.first, let url = match.url {
            UIApplication.shared.open(url)
        }
    }
}

画面ではこのように出力できます。現在はtintColor(デフォルトの色)で表示していますが、カスタムで様々な色に変更することができます。

Screenshot 2025-02-14 at 12.28.21 AM.png

3.おわりに
初めてのQiitaを書いたので、見にくかったり、分かりにくかったかもしれません。
今後アップデートして改善していくので、よろしくお願いします。

私がiOS/Androidを開発したhttps://IDNect.com もよろしくお願いします

2
0
1

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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?