Created
June 15, 2025 13:58
-
-
Save theoknock/f9f4b8d7a66c4652356a58aa22e71cc9 to your computer and use it in GitHub Desktop.
Displays Swift code with syntax highlighting
This file contains hidden or 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 | |
import HighlightSwift | |
struct SwiftSyntaxHighlighting: View { | |
@State private var code: String = """ | |
struct Example { | |
var text = "Hello, world!" | |
func greet() { | |
print(text) | |
} | |
} | |
""" | |
var body: some View { | |
SyntaxTextView(code: $code) | |
.font(.system(.body, design: .monospaced)) | |
.padding() | |
// Attribution at bottom | |
VStack(spacing: 2) { | |
Text("James Alan Bush") | |
.font(.caption) | |
.foregroundColor(.primary) | |
Text("Commit ID 68bcd48") | |
.font(.caption2) | |
.foregroundColor(.secondary) | |
} | |
.padding(.bottom, 8) | |
} | |
} | |
struct SyntaxTextView: UIViewRepresentable { | |
@Binding var code: String | |
let highlighter = Highlight() | |
func makeUIView(context: Context) -> UITextView { | |
let textView = UITextView() | |
textView.isEditable = true | |
textView.isSelectable = true | |
textView.backgroundColor = .white | |
textView.textColor = .label | |
textView.font = UIFont.monospacedSystemFont(ofSize: UIFont.systemFontSize, weight: .regular) | |
textView.delegate = context.coordinator | |
textView.autocapitalizationType = .none | |
textView.autocorrectionType = .no | |
return textView | |
} | |
func updateUIView(_ uiView: UITextView, context: Context) { | |
Task { | |
let attributed = try await highlighter.attributedText(code, language: "swift") | |
uiView.attributedText = NSAttributedString(attributed) | |
} | |
} | |
func makeCoordinator() -> Coordinator { | |
Coordinator(self) | |
} | |
class Coordinator: NSObject, UITextViewDelegate { | |
var parent: SyntaxTextView | |
init(_ parent: SyntaxTextView) { | |
self.parent = parent | |
} | |
func textViewDidChange(_ textView: UITextView) { | |
parent.code = textView.text | |
// Capture the current cursor offset | |
guard let selectedRange = textView.selectedTextRange else { return } | |
let cursorOffset = textView.offset(from: textView.beginningOfDocument, to: selectedRange.start) | |
Task { @MainActor in | |
let attributed = try await parent.highlighter.attributedText(parent.code, language: "swift") | |
textView.attributedText = NSAttributedString(attributed) | |
// Restore cursor position at the same offset | |
if let newPosition = textView.position(from: textView.beginningOfDocument, offset: cursorOffset) { | |
textView.selectedTextRange = textView.textRange(from: newPosition, to: newPosition) | |
} | |
} | |
} | |
} | |
} | |
#Preview { | |
SwiftSyntaxHighlighting() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment