-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDynamicTextEditor.swift
More file actions
66 lines (55 loc) · 1.77 KB
/
DynamicTextEditor.swift
File metadata and controls
66 lines (55 loc) · 1.77 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
import SwiftUI
struct DynamicTextEditor: View {
@State private var editingText = ""
var placeholder = "Enter text here..."
var miinHeight: CGFloat = 40
var maaxHeight: CGFloat = 200
var textFont: Font = .body
@State private var textHeight: CGFloat = 0
var body: some View {
ZStack(alignment: .topLeading) {
backendTextLabel
TextEditor(text: $editingText)
.font(textFont)
.frame(height: min(max(textHeight, miinHeight), maaxHeight))
.scrollContentBackground(.hidden)
.overlay(alignment: .topLeading) {
placeholderLabel
}
}
}
@ViewBuilder
var backendTextLabel: some SwiftUI.View {
Text(editingText)
.font(textFont)
.padding(.horizontal, 4)
.padding(.vertical, 12)
.background(
GeometryReader { geometry in
Color.clear.onAppear {
textHeight = geometry.size.height
}
.onChange(of: editingText) { _ in
textHeight = geometry.size.height
}
}
)
.opacity(0)
.allowsHitTesting(false)
}
@ViewBuilder
var placeholderLabel: some SwiftUI.View {
Text(placeholder)
.font(textFont)
.foregroundColor(Color.gray.opacity(0.5))
.padding(.leading, 4)
.padding(.top, 8)
.allowsHitTesting(false)
.opacity(editingText.isEmpty ? 1.0 : 0)
}
}
#Preview {
DynamicTextEditor()
.background(Color.gray.opacity(0.1))
.padding()
}