-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUIKitTextEditor.swift
More file actions
332 lines (279 loc) · 9.95 KB
/
UIKitTextEditor.swift
File metadata and controls
332 lines (279 loc) · 9.95 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
//
// UIKitTextEditor.swift
// DevLog
//
// Created by opfic on 3/18/26.
//
import SwiftUI
import UIKit
struct UIKitTextEditor: View {
@Binding var text: String
@Environment(\.uiKitTextEditorFocusBinding) private var focusBinding
@State private var minHeight = TextEditorMetrics.font.lineHeight
private let placeholder: String
init(
text: Binding<String>,
placeholder: String = ""
) {
self._text = text
self.placeholder = placeholder
}
var body: some View {
UIKitTextEditorRepresentable(
text: $text,
minHeight: $minHeight,
focusBinding: focusBinding,
placeholder: placeholder
)
.frame(maxWidth: .infinity, minHeight: minHeight)
}
// 각 메서드 내에 있는 `.focused()`의 정체
// 해당 .focused()는 SwiftUI의 모디파이어
// 이 뷰를 SwiftUI 포커스 시스템에 실제 포커스 타겟으로 등록해주는 역할을 함
func focused(_ condition: FocusState<Bool>.Binding) -> some View {
modifier(TextEditorFocusModifier(
focusBinding: Binding(condition)
))
.focused(condition)
}
func focused<Value>(
_ binding: FocusState<Value>.Binding,
equals value: Value
) -> some View where Value: Hashable & ExpressibleByNilLiteral {
modifier(TextEditorFocusModifier(
focusBinding: Binding(
binding,
equals: value
)
))
.focused(binding, equals: value)
}
}
private enum TextEditorMetrics {
static let font = UIFont.preferredFont(forTextStyle: .body)
}
private struct TextEditorFocusModifier: ViewModifier {
let focusBinding: Binding<Bool>
func body(content: Content) -> some View {
content
.environment(\.uiKitTextEditorFocusBinding, focusBinding)
}
}
private struct TextEditorFocusBindingKey: EnvironmentKey {
static let defaultValue: Binding<Bool>? = nil
}
private extension EnvironmentValues {
var uiKitTextEditorFocusBinding: Binding<Bool>? {
get { self[TextEditorFocusBindingKey.self] }
set { self[TextEditorFocusBindingKey.self] = newValue }
}
}
private struct UIKitTextEditorRepresentable: UIViewRepresentable {
@Binding var text: String
@Binding var minHeight: CGFloat
private let focusBinding: Binding<Bool>?
private let placeholder: String
init(
text: Binding<String>,
minHeight: Binding<CGFloat>,
focusBinding: Binding<Bool>?,
placeholder: String
) {
self._text = text
self.focusBinding = focusBinding
self._minHeight = minHeight
self.placeholder = placeholder
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIView(context: Context) -> UITextView {
let textView = UITextView()
textView.delegate = context.coordinator
textView.font = TextEditorMetrics.font
textView.backgroundColor = .clear
textView.textColor = .label
textView.tintColor = .tintColor
textView.textContainer.lineFragmentPadding = 0
textView.textContainer.widthTracksTextView = true
textView.textContainer.lineBreakMode = .byWordWrapping
textView.textContainerInset = .zero
textView.isScrollEnabled = false
textView.autocorrectionType = .no
textView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
textView.setContentHuggingPriority(.defaultLow, for: .horizontal)
context.coordinator.applyPlaceholderIfNeeded(to: textView)
return textView
}
func updateUIView(_ uiView: UITextView, context: Context) {
context.coordinator.parent = self
if !context.coordinator.isShowingPlaceholder(in: uiView) && uiView.text != text {
uiView.text = text
}
context.coordinator.applyPlaceholderIfNeeded(to: uiView)
DispatchQueue.main.async {
if let focusBinding {
if focusBinding.wrappedValue {
if !uiView.isFirstResponder {
context.coordinator.startTrackingOffset(for: uiView)
uiView.becomeFirstResponder()
}
} else if uiView.isFirstResponder {
uiView.resignFirstResponder()
}
}
context.coordinator.updateHeight(for: uiView)
}
}
final class Coordinator: NSObject, UITextViewDelegate {
var parent: UIKitTextEditorRepresentable
private weak var scrollView: UIScrollView?
private var offsetObservation: NSKeyValueObservation?
private var trackedOffset: CGPoint?
private var isRestoringOffset = false
init(_ parent: UIKitTextEditorRepresentable) {
self.parent = parent
}
func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
startTrackingOffset(for: textView)
return true
}
func textViewDidBeginEditing(_ textView: UITextView) {
if isShowingPlaceholder(in: textView) {
textView.text = nil
textView.textColor = .label
}
if let focusBinding = parent.focusBinding, !focusBinding.wrappedValue {
focusBinding.wrappedValue = true
}
restoreOffsetIfNeeded()
DispatchQueue.main.async { [weak self] in
self?.restoreOffsetIfNeeded()
self?.updateHeight(for: textView)
}
}
func textViewDidChange(_ textView: UITextView) {
stopTrackingOffset()
parent.text = textView.text
updateHeight(for: textView)
}
func textViewDidEndEditing(_ textView: UITextView) {
if let focusBinding = parent.focusBinding, focusBinding.wrappedValue {
focusBinding.wrappedValue = false
}
stopTrackingOffset()
applyPlaceholderIfNeeded(to: textView)
}
func applyPlaceholderIfNeeded(to textView: UITextView) {
if parent.text.isEmpty && !textView.isFirstResponder {
textView.text = parent.placeholder
textView.textColor = .placeholderText
} else if isShowingPlaceholder(in: textView) {
textView.text = parent.text
textView.textColor = .label
}
}
func isShowingPlaceholder(in textView: UITextView) -> Bool {
textView.textColor == .placeholderText
}
func startTrackingOffset(for textView: UITextView) {
stopObservingOffset()
scrollView = textView.enclosingScrollView
trackedOffset = scrollView?.contentOffset
observeOffsetIfNeeded()
}
func restoreOffsetIfNeeded() {
guard let scrollView, let trackedOffset else { return }
if scrollView.contentOffset != trackedOffset {
isRestoringOffset = true
scrollView.setContentOffset(trackedOffset, animated: false)
isRestoringOffset = false
}
}
func observeOffsetIfNeeded() {
guard let scrollView else { return }
offsetObservation = scrollView.observe(
\.contentOffset,
options: [.new]
) { [weak self] scrollView, _ in
self?.handleOffsetChange(in: scrollView)
}
}
func handleOffsetChange(in scrollView: UIScrollView) {
guard let trackedOffset else {
stopObservingOffset()
return
}
if scrollView.isTracking || scrollView.isDragging || scrollView.isDecelerating {
stopTrackingOffset()
return
}
if isRestoringOffset {
return
}
if scrollView.contentOffset != trackedOffset {
restoreOffsetIfNeeded()
}
}
func stopObservingOffset() {
offsetObservation?.invalidate()
offsetObservation = nil
}
func stopTrackingOffset() {
stopObservingOffset()
scrollView = nil
trackedOffset = nil
}
func updateHeight(for textView: UITextView) {
textView.layoutIfNeeded()
let width = textView.bounds.width
guard 0 < width else { return }
let nextHeight = ceil(textView.sizeThatFits(
CGSize(width: width, height: .greatestFiniteMagnitude)
).height)
let resolvedHeight = max(nextHeight, TextEditorMetrics.font.lineHeight)
if parent.minHeight != resolvedHeight {
DispatchQueue.main.async {
self.parent.minHeight = resolvedHeight
}
}
}
}
}
private extension Binding where Value == Bool {
init(_ binding: FocusState<Bool>.Binding) {
self.init(
get: { binding.wrappedValue },
set: { binding.wrappedValue = $0 }
)
}
init<FocusedValue>(
_ binding: FocusState<FocusedValue>.Binding,
equals value: FocusedValue
) where FocusedValue: Hashable & ExpressibleByNilLiteral {
self.init(
get: {
binding.wrappedValue == value
},
set: { isFocused in
if isFocused {
binding.wrappedValue = value
} else if binding.wrappedValue == value {
binding.wrappedValue = nil
}
}
)
}
}
private extension UIView {
var enclosingScrollView: UIScrollView? {
var currentSuperview = superview
while let view = currentSuperview {
if let scrollView = view as? UIScrollView {
return scrollView
}
currentSuperview = view.superview
}
return nil
}
}