gpt4 book ai didi

ios - NavigationBar 中的 UISearchBar 颜色

转载 作者:行者123 更新时间:2023-11-29 11:27:31 25 4
gpt4 key购买 nike

我觉得我正在服用疯狂的药片。我想更改 UISearchBar 中文本字段的颜色,它位于 UINavigationBar 中。我遇到的问题是 UISearchBar 获得了 UINavigationBar 的颜色,但 TextField 没有改变颜色。我在这里尝试了几种解决方案,但似乎都没有解决问题。对如何更改 TextField 的颜色有任何想法吗?

我知道还有其他类似的问题,但我已经尝试了我遇到的所有可能的解决方案,但没有找到解决我的问题的方法。

Current Nav Bar with Attempted Bar tint

当前代码:

        let sc = UISearchController(searchResultsController: nil)
sc.delegate = self
let scb = sc.searchBar
scb.tintColor = UIColor.green
scb.barTintColor = UIColor.yellow


if let textfield = scb.value(forKey: "searchField") as? UITextField {
textfield.textColor = UIColor.blue
if let backgroundview = textfield.subviews.first {

// Background color
backgroundview.backgroundColor = UIColor.red

// Rounded corner
backgroundview.layer.cornerRadius = 5;
backgroundview.clipsToBounds = true;

}
}

navigationController?.navigationBar.barTintColor = UIColor.blue

navigationItem.searchController = sc
navigationItem.hidesSearchBarWhenScrolling = false

我创建了一个 sample project在行动中展示它。任何帮助或指导将不胜感激!

最佳答案

如果您想在更多 Controller 中使用这些设置,也许最好的解决方案是为 UISearchBar 创建一个扩展。这里有一些例子。

extension UISearchBar {

private func getViewElement<T>(type: T.Type) -> T? {

let svs = subviews.flatMap { $0.subviews }
guard let element = (svs.filter { $0 is T }).first as? T else { return nil }
return element
}

func getSearchBarTextField() -> UITextField? {
return getViewElement(type: UITextField.self)
}

func setTextColor(color: UIColor) {

if let textField = getSearchBarTextField() {
textField.textColor = color
}
}

func setTextFieldColor(color: UIColor) {

if let textField = getViewElement(type: UITextField.self) {
switch searchBarStyle {
case .minimal:
textField.layer.backgroundColor = color.cgColor
textField.layer.cornerRadius = 6
case .prominent, .default:
textField.backgroundColor = color
@unknown default:
print("something")
}
}
}

func setPlaceholderTextColor(color: UIColor) {

if let textField = getSearchBarTextField() {
textField.attributedPlaceholder = NSAttributedString(string: self.placeholder != nil ? self.placeholder! : "", attributes: [NSAttributedString.Key.foregroundColor: color])
}
}

func setTextFieldClearButtonColor(color: UIColor) {

if let textField = getSearchBarTextField() {

let button = textField.value(forKey: "clearButton") as! UIButton
if let image = button.imageView?.image {
button.setImage(image.transform(withNewColor: color), for: .normal)
}
}
}

func setSearchImageColor(color: UIColor) {

if let imageView = getSearchBarTextField()?.leftView as? UIImageView {
imageView.image = imageView.image?.transform(withNewColor: color)
}
}
}

更新:

navigationItem.searchController = sc 更改为 navigationItem.titleView = sc.searchBarenter image description here

关于ios - NavigationBar 中的 UISearchBar 颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57119195/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com