Apply ViewModifier to UIViewRepresentable
Asked Answered
J

1

7

I created a UIViewRespresentable for a UITextField. I'd like to apply modifiers:

myTextField.font(.headline).keyboardType(keyboardType)

This is not working, even if my UIViewRepresentable is simple:

class MyTextField: UITextField { ... }

struct MyFieldField: UIViewRepresentable {
    private let field = MyTextField()
    func makeUIView(context: Context) -> MyTextField { return field }
    func updateUIView(_ uiView: MyTextField, context: Context) {
        ...
    }
}
Jeopardous answered 12/11, 2019 at 21:6 Comment(0)
S
8

UITextField is a UIKit component, not a SwiftUI component. It doesn't currently respect .font() or any other SwiftUI modifiers. Furthermore, you cannot currently create a UIFont from a SwiftUI Font. So, although you can do @Environment(\.font) var font: Font to get the current value, you won't be able to do anything useful with it in UIKit land.

You can:

  1. Just set a UIFont directly on your UIViewRepresentable
  2. Use UIFont.TextStyle
  3. Map between Font.TextStyle and UIFont.TextStyle

With any of these you will need to explicitly create a variable on your UIViewRepresentable to hold that value, and then apply it during updateUIView(context:)

struct MyFieldField: UIViewRepresentable {
  // Your three options
  var myUIFont: UIFont
  var myUITextStyle: UIFont.TextStyle
  var mySwiftUITextStyle: Font.TextStyle // map this onto UIFont.TextStyle
  ...
}
Stenotype answered 13/11, 2019 at 6:22 Comment(1)
Thanks. I was hoping there was a way MyTextField could get the modifiers and go through them and apply them to the underlying UITextField (mapping them as you point out).Jeopardous

© 2022 - 2024 — McMap. All rights reserved.