将 ViewModifier 应用于 UIViewRepresentable [英] Apply ViewModifier to UIViewRepresentable

查看:51
本文介绍了将 ViewModifier 应用于 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.

您可以:

  1. 直接在你的 UIViewRepresentable
  2. 上设置一个 UIFont
  3. 使用UIFont.TextStyle
  4. Font.TextStyleUIFont.TextStyle
  5. 之间的映射
  1. Just set a UIFont directly on your UIViewRepresentable
  2. Use UIFont.TextStyle
  3. Map between Font.TextStyle and UIFont.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆