0

Say I have 2 TextFieldStyles like below where one of them should run with iOS 15+ if available.

struct TF1: TextFieldStyle {
    init()
    func _body(configuration: TextField<Self._Label>) -> some View {}
}
@available(iOS 15.0, *)
struct TF2: TextFieldStyle {
    @FocusState var focused: Bool
    
    init()
    func _body(configuration: TextField<Self._Label>) -> some View {}
}

Now I want to use theses style with modifier .textFieldStyle() where I pass in the right style.

For example

if #available(iOS 15.0, *) {
    TextField("").textFieldStyle(TF2())
} else {
    TextField("").textFieldStyle(TF1())
}

Above code works but can be improved. Is there a way to write an adapter so I can just do something like below?

   TextField("").textFieldStyle(Adapter())
oaranger
  • 169
  • 1
  • 11
  • 1
    put that conditional code inside `_body` and you'll have one style – Asperi Jun 23 '22 at 12:52
  • I need to have 2 styles since the one with iOS15 use the wrapper `@FocusState` and we can't declare like ``` @available(iOS 15.0, *) @FocusState var focused: Bool ``` – oaranger Jun 23 '22 at 12:57
  • You can use an [.if modifier](https://stackoverflow.com/questions/56517610/conditionally-use-view-in-swiftui/57685253#57685253) to achieve your goals and conditionally apply the appropriate `textFieldStyle` to your `TextField` – Dávid Pásztor Jun 23 '22 at 13:05

0 Answers0