-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathOverlayScrollView.swift
More file actions
45 lines (38 loc) · 1.78 KB
/
OverlayScrollView.swift
File metadata and controls
45 lines (38 loc) · 1.78 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
import SwiftUI
import AppKit
public struct OverlayScrollView<Content: View>: NSViewRepresentable {
let showsVerticalScroller: Bool
let showsHorizontalScroller: Bool
let content: Content
public init(showsVerticalScroller: Bool = true,
showsHorizontalScroller: Bool = false,
@ViewBuilder content: () -> Content) {
self.showsVerticalScroller = showsVerticalScroller
self.showsHorizontalScroller = showsHorizontalScroller
self.content = content()
}
public func makeNSView(context: Context) -> NSScrollView {
let scrollView = NSScrollView()
scrollView.drawsBackground = false
scrollView.hasVerticalScroller = showsVerticalScroller
scrollView.hasHorizontalScroller = showsHorizontalScroller
scrollView.autohidesScrollers = true
scrollView.scrollerStyle = .overlay
scrollView.verticalScrollElasticity = .automatic
scrollView.horizontalScrollElasticity = .automatic
let hosting = NSHostingView(rootView: content)
hosting.translatesAutoresizingMaskIntoConstraints = false
scrollView.documentView = hosting
if let docView = scrollView.contentView.documentView {
docView.leadingAnchor.constraint(equalTo: scrollView.contentView.leadingAnchor).isActive = true
docView.trailingAnchor.constraint(equalTo: scrollView.contentView.trailingAnchor).isActive = true
docView.topAnchor.constraint(equalTo: scrollView.contentView.topAnchor).isActive = true
}
return scrollView
}
public func updateNSView(_ nsView: NSScrollView, context: Context) {
if let hosting = nsView.documentView as? NSHostingView<Content> {
hosting.rootView = content
}
}
}