DefaultTextField.swift 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. //
  2. // Copyright © 2022 osy. All rights reserved.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. //
  16. import SwiftUI
  17. struct DefaultTextField: View {
  18. private let titleKey: LocalizedStringKey
  19. private let text: Binding<String>
  20. private let prompt: LocalizedStringKey
  21. private let onEditingChanged: (Bool) -> Void
  22. init(_ titleKey: LocalizedStringKey, text: Binding<String>, prompt: LocalizedStringKey = "", onEditingChanged: @escaping (Bool) -> Void = { _ in }) {
  23. self.titleKey = titleKey
  24. self.text = text
  25. self.prompt = prompt
  26. self.onEditingChanged = onEditingChanged
  27. }
  28. var body: some View {
  29. let stack = HStack {
  30. Text(titleKey)
  31. if titleKey.localizedString.count > 0 {
  32. Spacer()
  33. }
  34. TextField(prompt, text: text, onEditingChanged: onEditingChanged)
  35. }
  36. #if os(macOS)
  37. if #available(iOS 15, macOS 12, *) {
  38. DefaultTextFieldNew(titleKey, text: text, prompt: prompt, onEditingChanged: onEditingChanged)
  39. } else {
  40. stack
  41. }
  42. #else
  43. stack
  44. #endif
  45. }
  46. }
  47. @available(iOS 15, macOS 12, *)
  48. struct DefaultTextFieldNew: View {
  49. private let titleKey: LocalizedStringKey
  50. @Binding var text: String
  51. private let prompt: LocalizedStringKey
  52. private let onEditingChanged: (Bool) -> Void
  53. @FocusState private var focused: Bool
  54. init(_ titleKey: LocalizedStringKey, text: Binding<String>, prompt: LocalizedStringKey = "", onEditingChanged: @escaping (Bool) -> Void = { _ in }) {
  55. self.titleKey = titleKey
  56. self._text = text
  57. self.prompt = prompt
  58. self.onEditingChanged = onEditingChanged
  59. }
  60. var body: some View {
  61. TextField(titleKey, text: $text, prompt: Text(prompt))
  62. .focused($focused)
  63. .onChange(of: text) { newValue in
  64. onEditingChanged(focused)
  65. }
  66. .onSubmit {
  67. focused = false
  68. onEditingChanged(false)
  69. }
  70. }
  71. }
  72. struct DefaultTextField_Previews: PreviewProvider {
  73. static var previews: some View {
  74. DefaultTextField("Test", text: .constant("Value"), prompt: "Prompt")
  75. }
  76. }