Skip to content

Commit 304d285

Browse files
authored
Add Switch UIViewRepresentable (#107)
1 parent e4a618c commit 304d285

File tree

2 files changed

+96
-0
lines changed

2 files changed

+96
-0
lines changed

Sources/OpenSwiftUI/Integration/Representable/Platform/PlatformViewRepresentable.swift

+10
Original file line numberDiff line numberDiff line change
@@ -57,3 +57,13 @@ struct PlatformViewRepresentableContext<RepresentableType: PlatformViewRepresent
5757
var values: PlatformViewRepresentableValues
5858
let coordinator: RepresentableType.Coordinator
5959
}
60+
61+
62+
// TODO
63+
class PlatformViewCoordinator: NSObject {
64+
// var weakDispatchUpdate: (()->Void) -> Void
65+
66+
override init() {
67+
super.init()
68+
}
69+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
//
2+
// Switch.swift
3+
// OpenSwiftUI
4+
//
5+
// Audited for RELEASE_2021
6+
// Status: Blocked by Color
7+
// ID: 1246D37251EA3A918B392E2B95F8B7EF
8+
9+
#if os(iOS)
10+
import UIKit
11+
12+
// FIXME
13+
struct Color {}
14+
15+
private struct Switch: UIViewRepresentable {
16+
typealias UIViewType = UISwitch
17+
typealias Coordinator = PlatformSwitchCoordinator
18+
19+
@Binding var isOn: Bool
20+
var tint: Color?
21+
22+
func makeUIView(context: Context) -> UISwitch {
23+
let view = UISwitch()
24+
view.addTarget(
25+
context.coordinator,
26+
action: #selector(PlatformSwitchCoordinator.isOnChanged),
27+
for: .valueChanged
28+
)
29+
return view
30+
}
31+
32+
func updateUIView(_ uiView: UISwitch, context: Context) {
33+
let isOn = isOn
34+
let animated: Bool
35+
if let animation = context.transaction.animation, !context.transaction.disablesAnimations {
36+
animated = true
37+
} else {
38+
animated = false
39+
}
40+
uiView.setOn(isOn, animated: animated)
41+
uiView.preferredStyle = .sliding
42+
43+
let color: UIColor?
44+
if let tint {
45+
// TODO: Resolve the color from the environment
46+
color = nil
47+
} else {
48+
color = nil
49+
}
50+
let onTintColor = uiView.onTintColor
51+
if let color {
52+
if onTintColor == nil || color != onTintColor {
53+
uiView.onTintColor = color
54+
}
55+
} else {
56+
if onTintColor != nil {
57+
uiView.onTintColor = nil
58+
}
59+
}
60+
context.coordinator._isOn = _isOn
61+
}
62+
63+
func makeCoordinator() -> Coordinator {
64+
PlatformSwitchCoordinator(isOn: _isOn)
65+
}
66+
67+
}
68+
69+
private class PlatformSwitchCoordinator: PlatformViewCoordinator {
70+
var _isOn: Binding<Bool>
71+
72+
init(isOn: Binding<Bool>) {
73+
_isOn = isOn
74+
super.init()
75+
}
76+
77+
@objc
78+
func isOnChanged(_ sender: UISwitch) {
79+
Update.perform {
80+
_isOn.wrappedValue = sender.isOn
81+
}
82+
sender.setOn(_isOn.wrappedValue, animated: true)
83+
}
84+
}
85+
86+
#endif

0 commit comments

Comments
 (0)