forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomScrollView.swift
More file actions
60 lines (53 loc) · 1.65 KB
/
CustomScrollView.swift
File metadata and controls
60 lines (53 loc) · 1.65 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
import AppKit
import SwiftUI
import Combine
/// Used to workaround a SwiftUI bug. https://github.com/intitni/CopilotForXcode/issues/122
struct CustomScrollView<Content: View>: View {
@ViewBuilder var content: () -> Content
@State var height: Double = 100
@AppStorage(\.useCustomScrollViewWorkaround) var useNSScrollViewWrapper
var body: some View {
if useNSScrollViewWrapper {
List {
content()
.listRowInsets(EdgeInsets(top: 0, leading: -8, bottom: 0, trailing: -8))
}
.listStyle(.plain)
.frame(idealHeight: height)
.background {
ComputeHeight(height: $height) {
content()
}
.frame(maxWidth: .infinity)
.opacity(0)
}
} else {
ScrollView {
content()
}
}
}
}
private struct ComputeHeight<Content: View>: NSViewRepresentable {
@Binding var height: Double
@ViewBuilder var content: () -> Content
func makeNSView(context: Context) -> NSView {
let view = NSView()
return view
}
func updateNSView(_ nsView: NSView, context: Context) {
updateHeight(nsView)
}
func updateHeight(_ nsView: NSView) {
let contentView = content()
let hostingView = NSHostingView(
rootView: contentView.frame(width: nsView.frame.width == 0 ? 200 : nsView.frame.width)
)
let size = hostingView.fittingSize
if height != size.height {
Task { @MainActor in
height = size.height
}
}
}
}