-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathCodeView.swift
More file actions
97 lines (72 loc) · 2.76 KB
/
CodeView.swift
File metadata and controls
97 lines (72 loc) · 2.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
//
// CodeView.swift
// StackOv (Components module)
//
// Created by Илья Князьков
// Copyright © 2021 Erik Basargin. All rights reserved.
//
import SwiftUI
import Highlightr
struct CodeView: UIViewRepresentable {
// MARK: - Nested types
private enum Constants {
static let codeFont = UIFont.init(name: "Menlo-Regular", size: 13)
}
typealias UIViewType = UITextView
// MARK: - Private properties
private let codeType: String?
private let code: String
private var textStorage = CodeAttributedString()
// MARK: - Initialization
init(codeType: String?, code: String) {
self.codeType = codeType
self.code = code
}
// MARK: - View
func makeUIView(context: Context) -> UITextView {
let (textContainer, layoutManager) = getTextContainerAndLayoutManager()
textStorage.language = codeType?.lowercased()
textStorage.addLayoutManager(layoutManager)
layoutManager.addTextContainer(textContainer)
return getTextView(with: code, container: textContainer)
}
func updateUIView(_ uiView: UITextView, context: Context) { }
// MARK: - Private properties
private func getTextView(with text: String, container: NSTextContainer) -> UITextView {
let textView = UITextView(frame: .zero, textContainer: container)
textView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
textView.autocorrectionType = .no
textView.autocapitalizationType = .none
textView.font = Constants.codeFont
textView.isEditable = false
textView.isScrollEnabled = false
textView.dataDetectorTypes = .all
textView.backgroundColor = .clear
textView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
textView.text = text
return textView
}
private func getTextContainerAndLayoutManager() -> (container: NSTextContainer, manager: NSLayoutManager) {
let textContainer = NSTextContainer(size: .zero)
textContainer.lineFragmentPadding = .zero
let layoutManager = NSLayoutManager()
return (textContainer, layoutManager)
}
}
// MARK: - Previews
struct CodeView_Previews: PreviewProvider {
static let code = ("""
func convertHtml() -> NSAttributedString {
guard let data = data(using: .utf8) else { return NSAttributedString() }
if let attributedString = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {
return attributedString
} else {
return NSAttributedString()
}
}
""")
static let codeType = "swift"
static var previews: some View {
CodeView(codeType: codeType, code: code)
}
}