【问题标题】:UISearchBar: changing background color of input fieldUISearchBar:更改输入字段的背景颜色
【发布时间】:2011-11-05 22:44:18
【问题描述】:

我正在尝试更改 UISearchBar 输入字段的背景颜色。这是您输入要搜索的文本的圆形视图,默认颜色为白色。我想把它改成灰色

我试过了:

for (UIView *subView in searchBar.subviews) {
    if ([subView isKindOfClass:NSClassFromString(@"UITextField")]) {
        UITextField *textField = (UITextField *)subView;
        [textField setBackgroundColor:[UIColor grayColor]];
    }

但它不起作用:(

我还尝试向 TextField 插入图像视图,但圆形视图似乎与 TextField 是分开的。那么,有什么线索吗?

【问题讨论】:

  • 你应该在不在 interfacebuilder 中的代码中创建搜索栏。我在从 IB 创建时遇到了同样的问题。所以使用代码创建搜索栏
  • 感谢您的回复。我会试试的
  • 啊哈哈,我做到了!我用图像设置了 textField.background,它起作用了,耶!

标签: ios iphone objective-c uisearchbar


【解决方案1】:

=)

for (UIView *subView in _searchBar.subviews) {
    for(id field in subView.subviews){
        if ([field isKindOfClass:[UITextField class]]) {
            UITextField *textField = (UITextField *)field;
            [textField setBackgroundColor:[UIColor grayColor]];
        }
    }
}

【讨论】:

    【解决方案2】:

    看功能:

    [searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:@"search_bar"] forState:UIControlStateNormal];
    

    【讨论】:

      【解决方案3】:

      在 Swift 2 和 iOS 9 中你可以调用:

      UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).backgroundColor = UIColor.darkGrey()
      

      斯威夫特 3:

      UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).backgroundColor = UIColor.darkGrey()
      

      【讨论】:

      【解决方案4】:

      Swift 3 中的解决方案:

      if let txfSearchField = searchController.searchBar.value(forKey: "_searchField") as? UITextField {
              txfSearchField.borderStyle = .none
              txfSearchField.backgroundColor = .lightGray
      }
      

      【讨论】:

        【解决方案5】:

        以swift4中的扩展为例:

        extension UISearchBar {
        
            var input : UITextField? {
        
                return findInputInSubviews(of: self)
            }
        
            func findInputInSubviews(of view: UIView) -> UITextField? {
                guard view.subviews.count > 0 else { return nil }
                for v in view.subviews {
                    if v.isKind(of: UITextField.self) {
                        return v as? UITextField
                    }
                    let sv = findInputInSubviews(of: v)
                    if sv != nil { return sv }
                }
                return nil
            }
        }
        

        用法:

        searchBar?.input?.layer.borderColor = color.cgColor
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-03-07
          • 1970-01-01
          • 1970-01-01
          • 2011-11-28
          • 2016-07-23
          • 1970-01-01
          相关资源
          最近更新 更多