在UISearchController iOS 11上使用背景图片

nom*_*oda 4 uinavigationcontroller swift uisearchcontroller

我正在UISearchController为自己实现一个,UITableView但我正在为iOS 11的自定义设置而苦苦挣扎。我的导航栏使用的是渐变图像背景,我希望搜索控制器能够匹配该渐变背景,但是我还没有找到一种设置背景图像的方法为UISearchController。它可以作为TableHeaderView在UISearchController上完美运行,但是在iOS 11中几乎没有传递任何自定义设置。

当前结果:

目前的结果

期望的结果:

期望的结果

这是我正在使用的代码:( 在viewDidLoad上调用)

private func setupSearchController() {

    let searchController = UISearchController(searchResultsController: nil)

    // Convert CAGradientLayer to UIImage
    let gradient = Color.blue.gradient
    gradient.frame = searchController.searchBar.bounds
    UIGraphicsBeginImageContext(gradient.bounds.size)
    gradient.render(in: UIGraphicsGetCurrentContext()!)
    let gradientImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    // Setup the Search Controller
    searchController.searchBar.backgroundImage = gradientImage
    searchController.searchBar.isTranslucent = false
    searchController.searchResultsUpdater = self
    searchController.hidesNavigationBarDuringPresentation = false
    searchController.dimsBackgroundDuringPresentation = false
    searchController.obscuresBackgroundDuringPresentation = false
    searchController.searchBar.placeholder = "Search by transaction name"
    searchController.searchBar.tintColor = Color.custom(hexString: "FAFAFA", alpha: 1).value
    definesPresentationContext = true
    searchController.searchBar.delegate = self

    // Implement Search Controller
    if #available(iOS 11.0, *) {
        navigationItem.searchController = searchController
        navigationItem.hidesSearchBarWhenScrolling = false
        navigationController?.navigationBar.setBackgroundImage(gradientImage, for: .default)
    } else {
        tableView.tableHeaderView = searchController.searchBar
    }

}
Run Code Online (Sandbox Code Playgroud)

nom*_*oda 5

感谢Krunal的回答,我花了很长一段时间才找到了一个不错的解决方案。

这就是我实现iOS 11背景图片的方式:

    // Implement Search Controller
    if #available(iOS 11.0, *) {
        if let navigationBar = self.navigationController?.navigationBar {
            navigationBar.barTintColor = UIColor(patternImage: gradientImage!)
        }
        if let textField = searchController.searchBar.value(forKey: "searchField") as? UITextField {
            if let backgroundview = textField.subviews.first {
                backgroundview.backgroundColor = UIColor.white
                backgroundview.layer.cornerRadius = 10;
                backgroundview.clipsToBounds = true;

            }
        }
        navigationItem.searchController = searchController
        navigationItem.hidesSearchBarWhenScrolling = false
    } else {
        tableView.tableHeaderView = searchController.searchBar
    }
Run Code Online (Sandbox Code Playgroud)