【问题标题】:Setting the font of SwiftUI's .searchable() with the appearance API of UITextField+UISearchBar doesn't work用 UITextField+UISearchBar 的外观 API 设置 SwiftUI 的 .searchable() 的字体不起作用
【发布时间】:2022-10-20 14:47:14
【问题描述】:

我正在使用UISearchBar 的外观API 自定义SwiftUI 的.searchable() 修饰符的外观。

几乎所有东西都可以,除了文本字段的字体,我不知道为什么(设置取消按钮的字体有效,或者设置文本字段的背景颜色或文本颜色也有效,所以有正确的参考) .

说话很便宜,给我看代码!

let textAttributes: [NSAttributedString.Key: Any] = [
    .foregroundColor: UIColor.systemBlue,      // this works
    .font: UIFont.boldSystemFont(ofSize: 15)   // this doesnt
]
let placeholder = NSAttributedString(
    string: "Search...",                         // this doesnt
    attributes: [
        .foregroundColor: UIColor.systemGray,    // this works
        .font: UIFont.boldSystemFont(ofSize: 15) // this doesnt
])

let textFieldAppearance = UITextField
            .appearance(whenContainedInInstancesOf: [UISearchBar.self])
textFieldAppearance.backgroundColor = .red // this works
textFieldAppearance.defaultTextAttributes = textAttributes // color works, font not
textFieldAppearance.attributedPlaceholder = placeholder // color works, font or text not

我想是时候提交-radar-反馈了?

【问题讨论】:

    标签: swiftui uitextfield uisearchbar searchable uisearchbartextfield


    【解决方案1】:

    我还没有找到一种可靠的自定义方法,下面发布的解决方案在 SwiftUI 重新呈现视图(滚动或只是在搜索栏上键入)时,搜索栏上会出现故障,这在搜索栏上非常明显真实设备(在模拟器上没有那么多)。

    老答案:

    远非理想,我找到了一种让它工作的方法,即内省搜索UITextField 的视图并直接设置字体。最简单的方法是使用类似的库SwiftUI-内省(https://github.com/siteline/SwiftUI-Introspect)。

    然后在 View 上,您正在使用 .searchable() 来自:

    .introspectTextField { textField in
        textField.font = UIFont.boldSystemFont(ofSize: 15)
    }
    

    固定的!完美的解决方案是使用外观 API,但我想我们必须等到 iOS 16...

    【讨论】:

    • 在我的情况下,introspect 可以检测到textField,但是当我在此textField 上设置任何属性时,它不会被反映,例如textColorfonttextField 出现时根本没有任何变化
    【解决方案2】:

    .searchable 之后设置.font.foregroundColor 修饰符将达到预期的效果,但在撰写本文时(iOS 16)仍然无法使用.background 修饰符(如果需要)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-24
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多