Copied placeholder, focusOnStart, actionOnReturnKeyPress and textChanged from UIKitTextField to UIKitSearchBar

This commit is contained in:
dankito 2020-08-03 20:18:09 +02:00
parent 6a4f41a578
commit 9d1dbadd46
2 changed files with 60 additions and 8 deletions

View File

@ -38,7 +38,7 @@ struct SelectBankDialog: View {
Form {
Section {
VStack {
UIKitSearchBar(text: searchTextBinding) // TODO: try to get rid of the two horizontal lines
UIKitSearchBar(text: searchTextBinding, focusOnStart: true) // TODO: try to get rid of the two horizontal lines
HStack {
Text("Search by bank code, bank name or city")

View File

@ -5,11 +5,37 @@ struct UIKitSearchBar : UIViewRepresentable {
@Binding var text : String
private var placeholder: String
private var focusOnStart = false
private var actionOnReturnKeyPress: (() -> Bool)? = nil
private var textChanged: ((String) -> Void)? = nil
init(text: Binding<String>, placeholder: String = "", focusOnStart: Bool = false, actionOnReturnKeyPress: (() -> Bool)? = nil, textChanged: ((String) -> Void)? = nil) {
_text = text
self.placeholder = placeholder
self.focusOnStart = focusOnStart
self.actionOnReturnKeyPress = actionOnReturnKeyPress
self.textChanged = textChanged
}
func makeUIView(context: UIViewRepresentableContext<UIKitSearchBar>) -> UISearchBar {
let searchBar = UISearchBar(frame: .zero)
searchBar.placeholder = placeholder.localize()
searchBar.delegate = context.coordinator
searchBar.searchTextField.delegate = context.coordinator
if focusOnStart {
searchBar.becomeFirstResponder()
}
return searchBar
}
@ -18,22 +44,48 @@ struct UIKitSearchBar : UIViewRepresentable {
uiView.text = text
}
func makeCoordinator() -> Cordinator {
return Cordinator(text: $text, actionOnReturnKeyPress: actionOnReturnKeyPress, textChanged: textChanged)
}
class Cordinator : NSObject, UISearchBarDelegate {
class Cordinator : NSObject, UISearchBarDelegate, UITextFieldDelegate {
@Binding var text : String
init(text : Binding<String>) {
private var actionOnReturnKeyPress: (() -> Bool)?
private var textChanged: ((String) -> Void)?
init(text: Binding<String>, actionOnReturnKeyPress: (() -> Bool)? = nil, textChanged: ((String) -> Void)? = nil) {
_text = text
self.actionOnReturnKeyPress = actionOnReturnKeyPress
self.textChanged = textChanged
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
text = searchText
let newText = searchBar.text ?? ""
let didTextChange = newText != text // e.g. if just the cursor has been placed to another position then textFieldDidChangeSelection() gets called but text didn't change
DispatchQueue.main.async { // to not update state during view update
self.text = newText
if didTextChange {
self.textChanged?(newText)
}
}
}
}
func makeCoordinator() -> Cordinator {
return Cordinator(text: $text)
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return actionOnReturnKeyPress?() ?? false
}
}
}