无法更改UISearchBar的颜色?

时间:2019-01-27 15:56:32

标签: ios swift uitableview uicolor

我正在尝试更改searchBar的background-,tint-和barTintColor ...我尝试了许多不同的方法,但是没有一种起作用。我什至尝试将GlobalTintColor设置为所需的黄色。

当前代码:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    //UISearchController
    searchController.searchBar.delegate = self
    self.searchController.delegate = self
    searchController.searchResultsUpdater = self
    searchController.hidesNavigationBarDuringPresentation = false
    searchController.dimsBackgroundDuringPresentation = false
    searchController.searchBar.sizeToFit()
    searchController.searchBar.barTintColor = UIColor(red:1.00, green:0.96, blue:0.02, alpha:1.0)
    searchController.searchBar.tintColor = UIColor(red:1.00, green:0.96, blue:0.02, alpha:1.0)
    searchController.searchBar.backgroundColor = UIColor(red:0.36, green:0.39, blue:0.40, alpha:1.0)
    searchController.searchBar.placeholder = "Search for Users"

    if #available(iOS 9.1, *) {
        searchController.obscuresBackgroundDuringPresentation = false
    } else {
        // Fallback on earlier versions
    }

    if #available(iOS 11.0, *) {
        navigationItem.searchController = searchController
    } else {
        // Fallback on earlier versions
    }

    if #available(iOS 11.0, *) {
        self.navigationItem.searchController = self.searchController
        self.navigationItem.hidesSearchBarWhenScrolling = false
    } else {
        tableView.tableHeaderView = searchController.searchBar
    }
    self.navigationItem.titleView?.tintColor = UIColor.yellow
}

我有什么错误设置吗?

1 个答案:

答案 0 :(得分:0)

这样做:

func SearchBarAppearence() {
    searchController.searchBar.tintColor = .black
    searchController.searchBar.setValue("text of button", forKey:"_cancelButtonText")
    UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSAttributedStringKey.foregroundColor.rawValue: UIColor.white]
    UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).attributedPlaceholder = NSAttributedString(string: "text of searchbar", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])
    UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSAttributedStringKey.font.rawValue: UIFont(name: IRAN_SANS_MOBILE_FONT, size: 14)!]
    UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes([NSAttributedStringKey.font : UIFont(name: IRAN_SANS_MOBILE_FONT, size: 14)!], for: .normal)
}