无法更改搜索栏背景颜色

Ork*_*ade 19 uisearchbar ios swift

我有一个搜索栏:

let searchBar:UISearchBar = UISearchBar(frame: CGRectMake((searchView.frame.width - UIScreen.mainScreen().bounds.width / 1.6) / 2, 0, UIScreen.mainScreen().bounds.width / 1.6, 24))
Run Code Online (Sandbox Code Playgroud)

我想改变文字输入部分的背景颜色.为此,我尝试过:

searchBar.barTintColor = UIColor(red: 0/255, green: 74/255, blue: 103/255, alpha: 1)

searchBar.backgroundColor = UIColor.redColor()
Run Code Online (Sandbox Code Playgroud)

但这两种变体都不起作用.如何更改我的UISearchBar textInput部分的背景颜色以及我做错了什么?

Imr*_*ran 14

如果您只想在ViewController中更改它并且不希望其他任何地方生效,那么请使用

for view in searchBar.subviews {
            for subview in view.subviews {
                if subview .isKindOfClass(UITextField) {
                    let textField: UITextField = subview as! UITextField
                    textField.backgroundColor = UIColor.redColor()
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

但是如果你想让它在整个应用程序中进行更改并定位到iOS 9.0或更高版本,那么应该使用appearanceWhenContainedInInstancesOfClasses之类的

UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).backgroundColor = UIColor.redColor()
Run Code Online (Sandbox Code Playgroud)

  • 我不知道为什么,但它仍然没有改变颜色 (3认同)

Jos*_*hpy 14

我做了一个 UISearchBar 扩展和类别来自定义搜索栏中的文本。

兼容从 iOS 9 到 iOS 13。

斯威夫特 4+

import UIKit

extension UISearchBar {

    // Due to searchTextField property who available iOS 13 only, extend this property for iOS 13 previous version compatibility
    var compatibleSearchTextField: UITextField {
        guard #available(iOS 13.0, *) else { return legacySearchField }
        return self.searchTextField
    }

    private var legacySearchField: UITextField {
        if let textField = self.subviews.first?.subviews.last as? UITextField {
            // Xcode 11 previous environment
            return textField
        } else if let textField = self.value(forKey: "searchField") as? UITextField {
            // Xcode 11 run in iOS 13 previous devices
            return textField
        } else {
            // exception condition or error handler in here
            return UITextField()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

var searchController: UISearchController?
searchController?.searchBar.compatibleSearchTextField.textColor = UIColor.XXX
searchController?.searchBar.compatibleSearchTextField.backgroundColor = UIColor.XXX
Run Code Online (Sandbox Code Playgroud)

目标-C

UISearchBar+SearchTextField.h

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface UISearchBar (SearchTextField)

// Due to searchTextField property who available iOS 13 only, extend this property for iOS 13 previous version compatibility
@property (nonatomic, readonly) UITextField *compatibleSearchTextField;

@end

NS_ASSUME_NONNULL_END
Run Code Online (Sandbox Code Playgroud)

UISearchBar+SearchTextField.m

#import "UISearchBar+SearchTextField.h"

@implementation UISearchBar (SearchTextField)

- (UITextField *)compatibleSearchTextField {
    if (@available(iOS 13.0, *)) {
#ifdef __IPHONE_13_0
        return self.searchTextField;
#else
        // Xcode 11 run in iOS 13 previous devices
        return (UITextField *)[self valueForKey:@"searchField"];
#endif
    } else {
        // Xcode 11 previous environment
        return [[[self.subviews firstObject] subviews] lastObject];
    }
}

@end
Run Code Online (Sandbox Code Playgroud)

用法示例:

- (UISearchBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(X, X, X, X)];
        _searchBar.compatibleSearchTextField.textColor = [UIColor XXX];
        _searchBar.compatibleSearchTextField.backgroundColor = [UIColor XXX];
    }
    return _searchBar
}
Run Code Online (Sandbox Code Playgroud)


Kir*_*odi 10

您在ViewDidLoad中添加以下代码并更改文本字段背景颜色RED,

for subView in searchBar.subviews
{
    for subView1 in subView.subviews
    {

        if subView1.isKindOfClass(UITextField)
        {
            subView1.backgroundColor = UIColor.redColor()
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

SearchBar中TextField的红色.

在此输入图像描述


Ali*_*ien 10

对于Swift 3+,请使用:

for subView in searchController.searchBar.subviews {

    for subViewOne in subView.subviews {

        if let textField = subViewOne as? UITextField {

           subViewOne.backgroundColor = UIColor.red

           //use the code below if you want to change the color of placeholder
           let textFieldInsideUISearchBarLabel = textField.value(forKey: "placeholderLabel") as? UILabel
                textFieldInsideUISearchBarLabel?.textColor = UIColor.blue
        }
     }
}
Run Code Online (Sandbox Code Playgroud)


Jos*_*art 10

斯威夫特 5:

    searchController.searchBar.searchTextField.backgroundColor = .white
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案。1 条线路,工作完美,符合预期。没有什么花哨的东西,也没有解决方法。该主题的最佳答案 (2认同)
  • 这会在 iOS 12.x 下崩溃,这就是为什么其他答案更合适。 (2认同)
  • 在 iOS 16 上使用此功能没有崩溃。 (2认同)

Áng*_*lez 9

就像@aliamcami一样,之前的所有答案都没有我期望的那样有效,要么答案对我不起作用,要么它起作用,但是它需要太多的“虚拟”代码。因此,我分享了用简化的逻辑在Swift 4中写的另一个答案:

for textField in searchController.searchBar.subviews.first!.subviews where textField is UITextField {
    textField.subviews.first?.backgroundColor = .white
    textField.subviews.first?.layer.cornerRadius = 10.5 //I set 10.5 because is approximately the system value
    textField.subviews.first?.layer.masksToBounds = true
    //Continue changing more properties...
}
Run Code Online (Sandbox Code Playgroud)

textField.subviews.first是“ _UISearchBarSearchFieldBackgroundView”子视图,可在后面添加视觉效果UIFieldEditor。


已编辑

经过一些开发和许多错误之后,我完成了这个优雅的解决方案(我确信苹果不会批准,但我不知道),该解决方案可在iOS 10到iOS 12上运行:

if let textField = searchBar.value(forKey: "searchField") as? UITextField {
    textField.backgroundColor = myColor
    //textField.font = myFont
    //textField.textColor = myTextColor
    //textField.tintColor = myTintColor
    // And so on...

    let backgroundView = textField.subviews.first
    if #available(iOS 11.0, *) { // If `searchController` is in `navigationItem`
        backgroundView?.backgroundColor = UIColor.white.withAlphaComponent(0.3) //Or any transparent color that matches with the `navigationBar color`
        backgroundView?.subviews.forEach({ $0.removeFromSuperview() }) // Fixes an UI bug when searchBar appears or hides when scrolling
    }
    backgroundView?.layer.cornerRadius = 10.5
    backgroundView?.layer.masksToBounds = true
    //Continue changing more properties...
}
Run Code Online (Sandbox Code Playgroud)

当searchBar在tableHeaderView上面的代码可以被调用viewWillAppear,但如果是在navigationItemiOS上11及以上的,应该在被调用viewDidAppear。


Sup*_*ngo 8

仅使用Apple API执行此操作的方法是创建映像并使用setSearchFieldBackgroundImage:

self.searchBar.setSearchFieldBackgroundImage(UIImage(named: "SearchFieldBackground"), for: UIControlState.normal)
Run Code Online (Sandbox Code Playgroud)

如果您创建一个圆角矩形并动态显示和隐藏按钮,它甚至可以正确地为角设置动画.

使用此图片的示例: 在此输入图像描述

在此输入图像描述

  • backgroundColor对我没有任何改变 (2认同)

小智 8

面临同样的问题,对于iOS 13+,textFiled 可以通过如下方式获得

var searchText : UITextField?
if #available(iOS 13.0, *) {
   searchText  = searchBar.searchTextField
}
else {
    searchText = searchBar.value(forKey: "_searchField") as? UITextField
}
searchText?.backgroundColor = .red                                                              
Run Code Online (Sandbox Code Playgroud)


Tim*_*Dev 8

斯威夫特 5扩展:

适用于所有 iOS 版本

import UIKit

extension UISearchBar {

    func setupSearchBar(background: UIColor = .white, inputText: UIColor = .black, placeholderText: UIColor = .gray, image: UIColor = .black) {

        self.searchBarStyle = .minimal

        self.barStyle = .default

        // IOS 12 and lower:
        for view in self.subviews {

            for subview in view.subviews {
                if subview is UITextField {
                    if let textField: UITextField = subview as? UITextField {

                        // Background Color
                        textField.backgroundColor = background

                        //   Text Color
                        textField.textColor = inputText

                        //  Placeholder Color
                        textField.attributedPlaceholder = NSAttributedString(string: textField.placeholder ?? "", attributes: [NSAttributedString.Key.foregroundColor : placeholderText])

                        //  Default Image Color
                        if let leftView = textField.leftView as? UIImageView {
                            leftView.image = leftView.image?.withRenderingMode(.alwaysTemplate)
                            leftView.tintColor = image
                        }

                        let backgroundView = textField.subviews.first
                        backgroundView?.backgroundColor = background
                        backgroundView?.layer.cornerRadius = 10.5
                        backgroundView?.layer.masksToBounds = true

                    }
                }
            }

        }

        // IOS 13 only:
        if let textField = self.value(forKey: "searchField") as? UITextField {

            // Background Color
            textField.backgroundColor = background

            //   Text Color
            textField.textColor = inputText

            //  Placeholder Color
            textField.attributedPlaceholder = NSAttributedString(string: textField.placeholder ?? "", attributes: [NSAttributedString.Key.foregroundColor : placeholderText])

            //  Default Image Color
            if let leftView = textField.leftView as? UIImageView {
                leftView.image = leftView.image?.withRenderingMode(.alwaysTemplate)
                leftView.tintColor = image
            }

        }

    }

}
Run Code Online (Sandbox Code Playgroud)


小智 7

像这样

let searchBar:UISearchBar = UISearchBar(frame: CGRectMake((searchView.frame.width - UIScreen.mainScreen().bounds.width / 1.6) / 2, 0, UIScreen.mainScreen().bounds.width / 1.6, 24))
let searchTextField = searchBar.valueForKey("_searchField") as? UITextField
searchTextField?.backgroundColor = UIColor.redColor()
Run Code Online (Sandbox Code Playgroud)


Sud*_*ram 6

当我找到上述问题的解决方案时,我正在试验 searchBar 和 searchTextField 的属性。

下面,我列出了实现预期结果的步骤:

  1. 将searchTextField的边框样式设置为.none
  2. 将 searchTextField 的背景颜色设置为您想要的颜色
  3. 将searchTextField的图层的角半径更改为10
  4. 将 searchTextField 的 clipToBounds 属性设置为 true

此外,我提供了以下代码供您参考:

 let searchController = UISearchController(searchResultsController: nil)
 navigationItem.searchController = searchController

 searchController.searchBar.barTintColor = viewBackgroundColor
 searchController.searchBar.backgroundColor = viewBackgroundColor

 searchController.searchBar.searchTextField.borderStyle = .none
 searchController.searchBar.searchTextField.backgroundColor = .white
 searchController.searchBar.searchTextField.layer.cornerRadius = 10
 searchController.searchBar.searchTextField.clipsToBounds = true

Run Code Online (Sandbox Code Playgroud)

注意:searchTextField 处于 Beta 版,可在 iOS 13 上使用


Zac*_*lez 6

搜索栏颜色变化

只需将搜索栏样式更改为最小,它将显示搜索栏的背景颜色。更改框内的椭圆形(又称文本字段)。只需更改 searchbar.textfield.backgroundcolor 属性即可。

 searchbar.searchBarStyle = .minimal
 searchbar.backgroundColor = //color here                  
 searchbar.searchTextField.backgroundColor = //color here     
Run Code Online (Sandbox Code Playgroud)


Nos*_*vel 5

我这样做(Swift 3+解决方案):

let textFieldInsideSearchBar = searchBar.value(forKey: "searchField") as? UITextField
textFieldInsideSearchBar?.backgroundColor = UIColor.red
Run Code Online (Sandbox Code Playgroud)