Skip to content

Instantly share code, notes, and snippets.

@mattadatta
Created September 25, 2020 17:41
Show Gist options
  • Save mattadatta/4bfc267893e16d0ebc8bd86740d52b39 to your computer and use it in GitHub Desktop.
Save mattadatta/4bfc267893e16d0ebc8bd86740d52b39 to your computer and use it in GitHub Desktop.
//
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
//
import SwiftUI
import UIKit
struct UIKitTextField : UIViewRepresentable {
var title: String
@Binding var text: String
var onEditingChanged: (Bool) -> Void = { _ in }
var onCommit: () -> Void = {}
var introspect: (UITextField) -> Void = { _ in }
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIView(context: Context) -> UITextField {
let textField = UITextField()
textField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
textField.placeholder = self.title
textField.text = self.text
let coordinator = context.coordinator
textField.delegate = coordinator
textField.addTarget(coordinator, action: #selector(Coordinator.textFieldDidEndEditingOnExit(_:)), for: .editingDidEndOnExit)
self.introspect(textField)
return textField
}
func updateUIView(_ uiView: UITextField, context: Context) {
context.coordinator.text = self
uiView.placeholder = self.title
uiView.text = self.text
self.introspect(uiView)
}
final class Coordinator: NSObject, UITextFieldDelegate {
var text: UIKitTextField
init(_ text: UIKitTextField) {
self.text = text
}
func textFieldDidBeginEditing(_ textField: UITextField) {
self.text.onEditingChanged(true)
}
func textFieldDidEndEditing(_ textField: UITextField) {
self.text.onEditingChanged(false)
}
func textFieldDidChangeSelection(_ textField: UITextField) {
self.text.text = textField.text ?? ""
}
@objc func textFieldDidEndEditingOnExit(_ textField: UITextField) {
self.text.onCommit()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment