代码之家  ›  专栏  ›  技术社区  ›  derdida

是否设置UISearchBar的cornerRadius?

  •  3
  • derdida  · 技术社区  · 8 年前

    我想更改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在这里)

    1 回复  |  直到 8 年前
        1
  •  5
  •   Samah    8 年前

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

    if let textField = self.searchBar.subviews.first?.subviews.flatMap({ $0 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
    }
    

    请注意,如果苹果决定改变方式,这可能会在未来的iOS版本中出现突破 UISearchBar 文本字段是结构化的。

    已编辑为不使用 value(forKey:) .

    推荐文章