I have this SwiftUI UiViewRepresentable which I want to use to make a simple TextEditor with line numbers. However the line numbers don’t get drawn. I a very new to UIKit and this is most I was able to do. Can anyone please help me to draw the numbers. I also don’t need the last line number when the last line is empty. aka. n. Thanks in advance.
//
// Editor.swift
// Code+
//
// Created by Karl Ehrlich on 24.04.24.
//
import SwiftUI
class TextViewContainer: UITextView {
init(text: String) {
super.init(frame: .zero, textContainer: nil)
self.text = text
setupTextView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupTextView() {
backgroundColor = .white // Set background color to white
font = UIFont.monospacedSystemFont(ofSize: 15, weight: .regular) // Set font to monospaced system font
isEditable = true // Allow text editing
isSelectable = true // Allow text selection
dataDetectorTypes = .all // Enable data detection
}
override func layoutSubviews() {
super.layoutSubviews()
var currentLine = 1
layoutManager.enumerateLineFragments(forGlyphRange: NSRange(location: 0, length: textStorage.length)) { (rect, usedRect, textContainer, glyphRange, stop) in
print("Line: (currentLine)")
let attributes: [NSAttributedString.Key: Any] = [
.font: UIFont.monospacedSystemFont(ofSize: 12, weight: .light),
.foregroundColor : UIColor.gray,
]
let attributedString = NSAttributedString(string: "(currentLine)", attributes: attributes)
attributedString.draw(in: rect)
currentLine += 1
}
}
}
struct Editor: UIViewRepresentable {
@Binding var text: String
func makeUIView(context: Context) -> TextViewContainer {
let textView = TextViewContainer(text: text)
textView.contentInset = UIEdgeInsets(top: 0, left: 40, bottom: 0, right: 0) // Set content inset to indent by 40 pixels on the left
return textView
}
func updateUIView(_ uiView: TextViewContainer, context: Context) {
uiView.text = text
}
}
I tried to use a separate UIView but it also didn’t work. Here is my usage.
import SwiftUI
struct ContentView: View {
@State private var text = """
let a = 0
Hello, World!
This is my syntax highlighting editor using „TextKit 2“
"""
var body: some View {
Editor(text: $text)
}
}
#Preview {
ContentView()
}
New contributor
Stack Overflow is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.