Created
September 25, 2020 17:41
-
-
Save mattadatta/4bfc267893e16d0ebc8bd86740d52b39 to your computer and use it in GitHub Desktop.
This file contains 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
// | |
// 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