为 UISearchBar 设置 cornerRadius?

Set cornerRadius for UISearchBar?

我想更改 UISearchbar 的 cornerRadius 属性,但它不起作用。我试过:

if let textfield = searchBar.value(forKey: "searchField") as? UITextField {
        textfield.textColor = Color.text.primary // this is working
        if let backgroundView = textfield.subviews.first {
            backgroundView.layer.cornerRadius = 2 // not working
            backgroundView.clipsToBounds = true
        }
    }

有什么想法吗?如果我将 backgroundView 设置为另一种颜色,它会按预期工作(所以 BackgroundView 就在这里)

看起来背景视图具有强制圆角的自定义呈现代码。您可以尝试隐藏该视图,并手动配置文本字段以使其看起来相同。

if let textField = self.searchBar.subviews.first?.subviews.flatMap({ [=10=] as? UITextField }).first {
    textField.subviews.first?.isHidden = true
    textField.textColor = Color.text.primary
    textField.layer.backgroundColor = UIColor.white.cgColor
    textField.layer.cornerRadius = 2
    textField.layer.masksToBounds = true
}

请注意,如果 Apple 决定更改 UISearchBar 文本字段的结构方式,这可能会在 iOS 的未来版本中中断。

编辑为不使用 value(forKey:)