Last active
March 27, 2025 16:10
-
-
Save drucelweisse/72ec7ef51346b3036fc50c958bbcb140 to your computer and use it in GitHub Desktop.
SwiftUI UIViewRepresentable Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
final class UIKitTextField: UITextField {} | |
final class Box<T> { | |
var value: T | |
init(_ value: T) { | |
self.value = value | |
} | |
} | |
struct TextFieldProxy { | |
fileprivate var box: Box<UIKitTextField?> = Box(nil) | |
public var isFirstResponder: Bool { | |
box.value?.isFirstResponder ?? false | |
} | |
@discardableResult | |
public func becomeFirstResponder() -> Bool { | |
box.value?.becomeFirstResponder() ?? false | |
} | |
@discardableResult | |
public func resignFirstResponder() -> Bool { | |
box.value?.resignFirstResponder() ?? false | |
} | |
struct BoxKey: EnvironmentKey { | |
static var defaultValue: Box<UIKitTextField?>? = nil | |
} | |
} | |
private extension EnvironmentValues { | |
var textFieldBox: Box<UIKitTextField?>? { | |
get { | |
self[TextFieldProxy.BoxKey.self] | |
} | |
set { | |
self[TextFieldProxy.BoxKey.self] = newValue | |
} | |
} | |
} | |
public struct TextFieldReader<Content: View>: View { | |
@State private var proxy = TextFieldProxy() | |
private let content: (TextFieldProxy) -> Content | |
public init(@ViewBuilder content: @escaping (TextFieldProxy) -> Content) { | |
self.content = content | |
} | |
public var body: some View { | |
content(proxy) | |
.environment(\.textFieldBox, proxy.box) | |
} | |
} | |
public extension UIKitTextField { | |
struct SwiftUI: View { | |
var body: some View { | |
UIKitTextFieldRepresentable() | |
} | |
} | |
} | |
struct UIKitTextFieldRepresentable: UIViewRepresentable { | |
func makeUIView(context: Context) -> UIKitTextField { | |
let view = UIKitTextField() | |
return view | |
} | |
func updateUIView(_ uiView: UIKitTextField, context: Context) { | |
if context.environment.textfieldBox.value !== uiView { | |
context.environment.textfieldBox.value = uiView | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment