如何在UISearchController中更改文本字段的背景颜色?

时间:2018-12-13 13:06:42

标签: ios swift ios11 uisearchcontroller

如何在UISearchController搜索文本字段中更改默认的灰色背景?

屏幕截图

Screen shot

12 个答案:

答案 0 :(得分:5)

以下是有关如何设置textField背景的示例。

class ViewController: UIViewController {

    let searchController = UISearchController(searchResultsController: nil)

    private lazy var searchTextField: UITextField? = { [unowned self] in
        var textField: UITextField?
        self.searchController.searchBar.subviews.forEach({ view in
            view.subviews.forEach({ view in
                if let view  = view as? UITextField {
                    textField = view
                }
            })
        })
        return textField
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        searchController.obscuresBackgroundDuringPresentation = false
        searchController.searchBar.placeholder = "Search Candies"
        navigationItem.searchController = searchController
        definesPresentationContext = true

        if let bg = self.searchTextField?.subviews.first {
            bg.backgroundColor = .green
            bg.layer.cornerRadius = 10
            bg.clipsToBounds = true
        }
    }
}

结果

enter image description here

答案 1 :(得分:1)

要正确更新UISearchController的背景,请更改背景图像。

如果在可视调试器中看到UISearchController,则可以发现它的背景是UIImageView:

enter image description here

因此,您应该对搜索栏做小图像,然后将其设置为seachBar:

    lazy var searchController: UISearchController = {

        let searchController = UISearchController(searchResultsController: nil)

        searchController.searchBar.placeholder = "Search"
        searchController.searchBar.tintColor = UIColor.black
        searchController.searchBar.searchBarStyle = .minimal
        // Set background image to searchBar so it will resize
        searchController.searchBar.setSearchFieldBackgroundImage(UIImage(named: "oval_static"), for: .normal)

        definesPresentationContext = true

        return searchController
    }()

searchBar的图像(在项目中,我建议使用.pdf或.png格式的图像作为截图):

enter image description here

UISearchBar将根据需要调整其大小,结果为:

enter image description here

此外,我们可以执行以下操作以仅使用代码创建自定义背景:

/// Just random extension to make image from UIView, you can use your own
extension UIView {

func asImage() -> UIImage {
    let renderer = UIGraphicsImageRenderer(bounds: bounds)
    return renderer.image { rendererContext in
        layer.render(in: rendererContext.cgContext)
    }
}}

lazy var searchController: UISearchController = {

        let searchController = UISearchController(searchResultsController: nil)

        searchController.searchBar.placeholder = "Search"
        searchController.searchBar.tintColor = UIColor.black
        searchController.searchBar.searchBarStyle = .minimal

        // Create own view with custom properties
        // Default height is 36 points
        let differentColorSearchBar = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 36))

        differentColorSearchBar.layer.cornerRadius = 8
        differentColorSearchBar.clipsToBounds = true
        differentColorSearchBar.backgroundColor = UIColor.blue

        searchController.searchBar.setSearchFieldBackgroundImage(differentColorSearchBar.asImage(), for: .normal)

        definesPresentationContext = true

        return searchController
    }

结果是(当然,您可以更改searchBar的其他属性以使其更好,但我只是向您展示如何正确更改背景):

enter image description here

我建议您避免使用私有财产,而只能使用open!希望对您有所帮助。

答案 2 :(得分:0)

我这样做,Objective-C代码:

UITextField *searchField = [_navigationSearchBar valueForKey:@"searchField"];
searchField.backgroundColor = [UIColor defaultSeacrhBarColor];
searchField.textColor = [UIColor defaultWhiteColor];
searchField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:searchTitle];
UILabel *placeholderLabel = [searchField valueForKey:@"placeholderLabel"];
placeholderLabel.textColor = [UIColor lightTextColor];

UIButton *clearButton = [searchField valueForKey:@"clearButton"];
[clearButton setImage:[clearButton.imageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
clearButton.tintColor = [UIColor defaultWhiteColor];

_navigationSearchBar.delegate = self;
[_navigationSearchBar setTranslucent:NO];
[_navigationSearchBar setBackgroundImage:nil];
[_navigationSearchBar setBarTintColor:[UIColor defaultNavigationBarColor]];
[_navigationSearchBar setBackgroundColor:[UIColor defaultNavigationBarColor]];
[_navigationSearchBar setImage:[UIImage imageNamed:@"Search_Icon"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
_navigationSearchBar.clipsToBounds = YES;
[_navigationBar addSubview:_navigationSearchBar];

答案 3 :(得分:0)

Apple具有键“ searchField”以检测searchBar中的文本字段。因此,首先安全地获取该文本字段,然后使用文本字段进行所需的更改。

let searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.searchBar.placeholder = "Search here..."
searchController.searchBar.delegate = self
searchController.searchBar.tintColor = .white
searchController.searchBar.barTintColor = .white
searchController.hidesNavigationBarDuringPresentation = false
searchController.obscuresBackgroundDuringPresentation = false

if let textfield = searchController.searchBar.value(forKey: "searchField") as? UITextField {

    // Set text colour of text field   
    textfield.textColor = UIColor.blue

    if let backgroundview = textfield.subviews.first {

        // Get background view and change background color
        backgroundview.backgroundColor = UIColor.white

        // Set rounded corner
        backgroundview.layer.cornerRadius = 10
        backgroundview.clipsToBounds = true
    }
}

if #available(iOS 11.0, *) {
    self.navigationItem.searchController = searchController
} else {
    self.tblCustomers.tableHeaderView = searchController.searchBar
}

这是工作代码,我已经在当前项目中实现了。不过,如果您有任何疑问,请告诉我。

我希望这会对您有所帮助。

答案 4 :(得分:0)

Max使用以下功能更改颜色。

extension UISearchBar {
func setBackgroundColor(){
    if let view:UIView = self.subviews.first {
        for curr in view.subviews {
            guard let searchBarBackgroundClass = NSClassFromString("UISearchBarBackground") else {
                return
            }
            if curr.isKind(of:searchBarBackgroundClass){
                if let imageView = curr as? UIImageView{
                    imageView.backgroundColor = .red
                    break
                }
            }
        }
    }
}
}

通过搜索栏使用此功能。

searchBarController.searchBar.setBackgroundColor()

答案 5 :(得分:0)

没有任何适当/公开的方式可以更改此搜索栏的背景颜色。使用私有API的方法有很多,例如@sanjayshah的回答,但是在这种情况下,苹果有可能拒绝您的应用程序。我认为您应该继续使用默认背景色。大多数应用程序使用相同的内容。

答案 6 :(得分:0)

@Kamran答案的递归版本,具有最佳的最佳情况和平均运行时间。接受的版本对我而言不适用于iOS 13 +。

private lazy var searchTextField: UITextField? = { [unowned self] in
    guard let searchBar = self.searchController?.searchBar else { return nil }
    var views =  searchBar.subviews
    while !views.isEmpty {
        guard let view = views.popLast() else { break }
        if let textfield = view as? UITextField {
            return textfield
        }
        views += view.subviews
    }
    return nil
}()

答案 7 :(得分:0)

在iOS13和更高版本上,searchTextField是UISearchBar的成员。因此,您可以使用以下内容:

$terms = wp_get_object_terms($post->ID, $taxonomy, array('hide_empty' => false) );

答案 8 :(得分:0)

首先检查平台

比进行修改,因为IOS 13不接受许多针对IOS 12的技巧

if #available(iOS 13, *) {
   searchController.searchBar.searchTextField.backgroundColor = .white 
} else {

for textField in searchController.searchBar.subviews.first.subviews where   textField is UITextField {
textField.subviews.first.backgroundColor = .white
textField.subviews.first.layer.cornerRadius = 10
textField.subviews.first.layer.masksToBounds = true
  }
}

答案 9 :(得分:0)

在iOS 12及以下版本中,需要覆盖文本字段中的图像,该图像具有我们要更改的背景色。 您可以在imageview之后的索引1处添加自定义视图,以实现所需的功能。

if #available(iOS 13.0, *)
    {
        searchBar.searchTextField.textColor       = .black
        searchBar.searchTextField.backgroundColor = .red
    }
    else if let textFieldInsideSearchBar = searchBar.value(forKey: "searchField") as? UITextField
    {
        textFieldInsideSearchBar.textColor = .black
        let backgroundView = UIView(frame: textFieldInsideSearchBar.bounds)
        backgroundView.backgroundColor = .red
        backgroundView.layer.cornerRadius = 10
        backgroundView.clipsToBounds = true
        textFieldInsideSearchBar.insertSubview(backgroundView, at: 1)
    }

答案 10 :(得分:-2)

您尝试过

searchController.searchBar.backgroundColor = UIColor.blue

答案 11 :(得分:-3)

只需执行以下操作:

searchController.searchBar.barTintColor = UIColor("Your color")
相关问题