将 ViewModifier 应用于 UIViewRepresentable [英] Apply ViewModifier to UIViewRepresentable
问题描述
我为 UITextField 创建了一个 UIViewRespresentable.我想应用修饰符:
I created a UIViewRespresentable for a UITextField. I'd like to apply modifiers:
myTextField.font(.headline).keyboardType(keyboardType)
这不起作用,即使我的 UIViewRepresentable 很简单:
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) {
...
}
}
推荐答案
UITextField
是一个 UIKit 组件,而不是一个 SwiftUI 组件.它目前不尊重 .font()
或任何其他 SwiftUI 修饰符.此外,您目前无法从 SwiftUI UIFont
创建 UIFont
代码>字体代码>.因此,尽管您可以执行 @Environment(\.font) var font: Font
来获取当前值,但您将无法在 UIKit 领域使用它做任何有用的事情.
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.
您可以:
- 直接在你的
UIViewRepresentable
上设置一个 - 使用
UIFont.TextStyle
Font.TextStyle
和UIFont.TextStyle
之间的映射
UIFont
- Just set a
UIFont
directly on yourUIViewRepresentable
- Use
UIFont.TextStyle
- Map between
Font.TextStyle
andUIFont.TextStyle
对于其中任何一个,您都需要在 UIViewRepresentable
上显式创建一个变量来保存该值,然后在 updateUIView(context:)
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
...
}
这篇关于将 ViewModifier 应用于 UIViewRepresentable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!