无法更改搜索栏背景颜色

时间:2015-11-17 07:24:52

标签: ios swift uisearchbar

我有一个搜索栏:

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

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

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

searchBar.backgroundColor = UIColor.redColor()

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

22 个答案:

答案 0 :(得分:12)

如果您只想在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()
                }
            }
        }

但如果您希望在整个应用中进行更改并定位iOS 9.0或更高版本,则应使用appearanceWhenContainedInInstancesOfClasses,如

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

答案 1 :(得分:10)

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

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

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

}

SearchBar中TextField的红色。

enter image description here

答案 2 :(得分:9)

对于Swift 3+,请使用:

<?php
require('db.php');
$user = new user;
class user
{
    function unpaid($dbcon)
    { 
        $check = $dbcon->query("SELECT `status` FROM `users` WHERE `ID` = :id");
        $row = $check->fetch_assoc();
        $status= $row['status'];
        if($status == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    function paid($dbcon)
    { 
        $check = $dbcon->query("SELECT `status` FROM `users` WHERE `ID` = :id");
        $row = $check->fetch_assoc();
        $status= $row['status'];
        if($status == 1)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    function admin($dbcon)
    { 
        $check = $dbcon->query("SELECT `status` FROM `users` WHERE `ID` = :id");
        $row = $check->fetch_assoc();
        $status= $row['status'];
        if($status == 2)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}
?>    

答案 3 :(得分:7)

Swift 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
            }

        }

    }

}

答案 4 :(得分:7)

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

self.searchBar.setSearchFieldBackgroundImage(UIImage(named: "SearchFieldBackground"), for: UIControlState.normal)

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

使用此图片的示例:enter image description here

enter image description here

答案 5 :(得分:6)

就像这样

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()

答案 6 :(得分:4)

就像@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...
}

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


已编辑

经过一些开发和许多错误之后,我完成了在 iOS 10上运行的优雅解决方案(我确定Apple不会批准,但我不知道)。 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...
}

searchBar位于tableHeaderView中时,可以在viewWillAppear中调用上述代码,但是如果它位于iOS 11及更高版本的navigationItem中,则应为在viewDidAppear中被调用。

答案 7 :(得分:4)

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

let textFieldInsideSearchBar = searchBar.value(forKey: "searchField") as? UITextField
textFieldInsideSearchBar?.backgroundColor = UIColor.red

答案 8 :(得分:3)

FWIW我通过创建一个名为textField的计算变量来解决这个问题。

extension UISearchBar {
    var textField: UITextField? {
        return subviews.first?.subviews.first(where: { $0.isKind(of: UITextField.self) }) as? UITextField
    }
}

答案 9 :(得分:2)

网络上这个问题的一个非常常见的答案是上面描述的这个解决方案:

for subView in searchBar.subviews {
    for subViewInSubView in subView.subviews {   
        if subViewInSubView.isKindOfClass(UITextField) {
            subViewInSubView.backgroundColor = UIColor.purpleColor()
       }
    }
}

但它对我使用XCode 7和iOS 9并不起作用,我注意到网络上有许多人报告说它也不适合他们。我发现UITextField子视图没有被创建(或者至少它没有被添加为子视图),直到它被引用,并且可以通过占位符字段引用它的一种方式,例如,可以添加在搜索UITextField类的子视图之前的这一行:

searchBar.placeholder = searchBar.placeholder

答案 10 :(得分:2)

我做了一个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()
        }
    }
}

用法示例:

var searchController: UISearchController?
searchController?.searchBar.compatibleSearchTextField.textColor = UIColor.XXX
searchController?.searchBar.compatibleSearchTextField.backgroundColor = UIColor.XXX

Objective-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

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

用法示例:

- (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
}

答案 11 :(得分:1)

设置您想要的任何颜色 SWIFT 3

public extension UISearchBar {
  public func setStyleColor(_ color: UIColor) {
    tintColor = color
    guard let tf = (value(forKey: "searchField") as? UITextField) else { return }
    tf.textColor = color
    if let glassIconView = tf.leftView as? UIImageView, let img = glassIconView.image {
      let newImg = img.blendedByColor(color)
      glassIconView.image = newImg
    }
    if let clearButton = tf.value(forKey: "clearButton") as? UIButton {
      clearButton.setImage(clearButton.imageView?.image?.withRenderingMode(.alwaysTemplate), for: .normal)
      clearButton.tintColor = color
    }
  }
}

extension UIImage {

  public func blendedByColor(_ color: UIColor) -> UIImage {
    let scale = UIScreen.main.scale
    if scale > 1 {
      UIGraphicsBeginImageContextWithOptions(size, false, scale)
    } else {
      UIGraphicsBeginImageContext(size)
    }
    color.setFill()
    let bounds = CGRect(x: 0, y: 0, width: size.width, height: size.height)
    UIRectFill(bounds)
    draw(in: bounds, blendMode: .destinationIn, alpha: 1)
    let blendedImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return blendedImage!
  }
}

答案 12 :(得分:1)

这是解决方案:

func customizeSearchBar(){
    if let textfield = searchController.searchbar.value(forKey: "searchField") as? UITextField {
        textfield.textColor = UIColor.blue
        if let backgroundview = textfield.subviews.first {

            // Background color
            backgroundview.backgroundColor = UIColor.white

            // Rounded corner
            backgroundview.layer.cornerRadius = 10;
            backgroundview.clipsToBounds = true;
        }
    }
}

但是请注意,这仅在iOS 11.0和更高版本中有效。 因此,不要忘记在此之前添加

if #available(iOS 11.0, *) {}

答案 13 :(得分:1)

基于Swift 4的UISearchBar扩展,基于投票最多的答案

extension UISearchBar {

    func tfBackgroundColor(color: UIColor){
        for view in self.subviews {
            for subview in view.subviews {
                if subview is UITextField {
                    let textField: UITextField = subview as! UITextField
                    textField.backgroundColor = color
                }
            }
        }
    }
    }

答案 14 :(得分:1)

当我找到上述解决方案时,我正在尝试使用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

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

答案 15 :(得分:1)

快捷键5:

    searchController.searchBar.searchTextField.backgroundColor = .white

答案 16 :(得分:0)

我只是分享了唯一一种可以更改搜索栏textField的背景颜色的方法,因为我还没有在任何答案上看到它,并且其他建议(无论是在本网站还是在其他站点)都对我没有帮助。

  • 从搜索栏中获取textField,就像@Steve的答案一样。只要您获取textField,这里的所有内容都可以使用。这不是我的问题,问题是,它不符合我在此处设置的颜色,无法正常工作 extension UISearchBar { var textField: UITextField? { return subviews.first?.subviews.first(where: { $0.isKind(of: UITextField.self) }) as? UITextField } }

  • 使用navigationBar的大小新建一个图层 let layer = CALayer() layer.backgroundColor = UIColor.white.withAlphaComponent(0.5).cgColor //Set your color here layer.frame = navigationBar.frame

  • 将新层设置为文本字段的子层 navigationBar.textField?.layer.masksToBounds = true //to make sure you get the rounded corners navigationBar.textField?.layer.cornerRadius = 14 //Round it as you wish navigationBar.textField?.layer.addSublayer(layer)
  • 就是这样,您将拥有一个具有任意颜色的圆形textField背景。

答案 17 :(得分:0)

这是解决方案

func configureSearchBar() {
    for textField in searchBar.subviews.first!.subviews where textField is UITextField {
        textField.backgroundColor = .cyan
    }
}

答案 18 :(得分:0)

遇到相同的问题,对于 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                                                              

答案 19 :(得分:0)

只需在游乐场尝试以下代码即可。如果仍然没有成功,请在您的问题中添加更多代码...

let searchView = UIView(frame: CGRect(x: 0.0,y: 0.0, width: 100, height: 50))

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

for subView in searchBar.subviews {
    for subViewInSubView in subView.subviews {   
        if subViewInSubView.isKindOfClass(UITextField) {
            subViewInSubView.backgroundColor = UIColor.purpleColor()
        }
    }
}

答案 20 :(得分:0)

搜索栏颜色变化

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

 searchbar.searchBarStyle = .minimal
 searchbar.backgroundColor = //color here                  
 searchbar.searchTextField.backgroundColor = //color here     

答案 21 :(得分:-1)

Swift 5 中,只需键入以下sh.ts :):D

self.personelSearchBar.searchTextField.backgroundColor = .white self.personelSearchBar.searchTextField.layer.borderWidth = 0.5 self.personelSearchBar.searchTextField.layer.cornerRadius = 3 self.personelSearchBar.searchTextField.layer.borderColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3).cgColor