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

问题描述 投票:3回答:8

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

屏幕截图

ios swift ios11 uisearchcontroller
8个回答
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


2
投票

要更新背景图像,更新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
    }()

搜索栏的图像(在项目中我建议使用.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

我建议避免私有属性只是使用开放!希望它有所帮助。


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];

0
投票

Apple有一个关键的'searchField'来检测searchBar中的文本字段。因此,首先要安全地获取该文本字段,然后使用textfield进行任何更改。

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
}

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

我希望这能帮到您。


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

0
投票

没有任何适当/公共方式来更改此搜索栏的背景颜色。有一些方法可以使用私有api,比如@sanjayshah的答案,但在这种情况下,苹果可能会拒绝您的申请。我认为你应该继续使用默认背景颜色。大多数应用程序使用相同的。


-2
投票

你尝试过类似的东西吗?

searchController.searchBar.backgroundColor = UIColor.blue

-3
投票

只需执行以下操作:

searchController.searchBar.barTintColor = UIColor("Your color")
© www.soinside.com 2019 - 2024. All rights reserved.