自定义navigationItem的searchController,但不适用于iOS 11

时间:2017-08-31 23:58:30

标签: ios customization uisearchbar uisearchcontroller ios11

我搜索了类似的问题UISearchController iOS 11 customization,但评论中的方法无法帮助我。所以我想再问一遍。

我使用以下代码设置searchBar的外观。

扩展UISearchBr以获取textField和placeHolderLabel:

extension UISearchBar{

    var textField: UITextField?{
        if let textField = self.value(forKey: "searchField") as? UITextField {

           return textField
        }
        return nil
    }

    var placehloderLabel:UILabel?{

        if let placeholderLabel = textField?.value(forKey: "placeholderLabel") as? UILabel{
            return placeholderLabel
    }
        return nil
    }
}

自定义UISearchController的子类:

class CustomSearchController:UISearchController{

    override init(searchResultsController: UIViewController?) {

        super.init(searchResultsController: searchResultsController)
        self.definesPresentationContext = true
        self.dimsBackgroundDuringPresentation = false
        self.hidesNavigationBarDuringPresentation = true
        self.searchBar.searchBarStyle = .minimal

        self.searchBar.placeholder = "搜索歌单内歌曲"
        self.searchBar.textField?.textColor = UIColor.white
        self.searchBar.placehloderLabel?.textColor = .white
        self.searchBar.placehloderLabel?.font = UIFont.systemFont(ofSize: 15)

    }

设置prefersLargeTitles UINavigationBar.appearance().prefersLargeTitles = true

如果navigationItem.searchController = searchController且结果如下(searchBar的外观 DOESN' T 进行更改): enter image description here

但如果我设置navigationItem.titleView = searchController.searchBar,它会: enter image description here

  

iOS 11是否允许开发人员更改searchBar   外观?如果是,我想知道如何定制它?任何   我很感激。谢谢!

1 个答案:

答案 0 :(得分:1)

Working with color and UINavigationItem's search controller

此代码位于AppDelegate类中。

UISearchBar.appearance().tintColor = UIColor(named: "Button") // using this to set the text color of the 'Cancel' button since the search bar ignores the global tint color property for some reason

if #available(iOS 11.0, *) {

      // Search bar placeholder text color
      UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).attributedPlaceholder = NSAttributedString(string: "Search", attributes: [NSForegroundColorAttributeName: UIColor.white])

     // Search bar text color
      UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSForegroundColorAttributeName: UIColor.red]

     // Insertion cursor color
      UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).tintColor = UIColor.red

        } else {
            // Fallback on earlier versions
        }

   // Search bar clear icon
      UISearchBar.appearance().setImage(UIImage(named: "clear"), for: .clear, state: .normal)