LoginSignup
3
3

【SwiftUI】Swiftのコードをシンタックスハイライトで表示する方法

Last updated at Posted at 2023-03-23

はじめに

検索できるChatGPT「ThinkMate」でシンタックスハイライトに対応しました。
今回は、そこで使用した技術をご紹介します。

作るもの

以下のようなコードビューアを作ります。
image.png

準備

Swift Package ManagerでSplashというライブラリをインストールします。

実装方法

以下は、Swiftのコードをシンタックスハイライトで表示するコードです。

import SwiftUI
import Splash

struct ContentView: View {
    let code = """
    import SwiftUI

    struct ContentView: View {
        var body: some View {
            VStack {
                Image(systemName: "globe")
                    .imageScale(.large)
                    .foregroundColor(.accentColor)
                Text("Hello, world!")
            }
        }
    }
    """

    var body: some View {
        codeView(code)
    }

    private func codeView(_ code: String) -> some View {
        let theme = Theme(
            font: Font(size: 20),
            plainTextColor: UIColor(.primary),
            tokenColors: [
                .keyword: UIColor(.pink),
                .string: UIColor(.orange),
                .type: UIColor(.indigo),
                .call: UIColor(.purple),
                .number: UIColor(.yellow),
                .comment: UIColor.lightGray,
                .property: UIColor(.teal),
                .dotAccess: UIColor(.teal),
                .preprocessing: UIColor.darkGray
            ]
        )

        let highlighter = SyntaxHighlighter(
            format: AttributedStringOutputFormat(theme: theme)
        )

        let attributedString = AttributedString(highlighter.highlight(code))

        return Text(attributedString)
    }
}

Splashというライブラリを使ってシンタックスハイライトを実現しました。

ポイントは以下の3点です。

  • Themeで色を指定
  • SyntaxHighlighterでハイライト
  • SyntaxHighlighter.highlightはNSAttributedStringであるため、Textで使えるAttributedStringに変換

おわり

以上のコードを実行することで、コードビューアができあがります。


ご覧いただきありがとうございました。

🐦 Twitter: @shota_appdev

📱 個人アプリ: Symbols Explorer

3
3
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
3
3