gpt4 book ai didi

ios - 如何在 UISearchController 中自定义 searchBar?

转载 作者:搜寻专家 更新时间:2023-10-30 22:11:02 24 4
gpt4 key购买 nike

我知道如何为独立的 UISearchBar 设置外观,就像下面这样。

    let searchField = searchBar.value(forKey: "searchField") as? UITextField

if let field = searchField {
field.backgroundColor = UIColor.defaultBackgroundColor
field.layer.cornerRadius = 15.0
field.textColor = .white
field.tintColor = .white

field.font = UIFont.systemFont(ofSize: fl(13))
field.layer.masksToBounds = true
field.returnKeyType = .search
}

但这在 UISearchController 中不起作用。

enter image description here

我想将占位符和左侧放大镜图标的文字颜色设置为纯白色。(现在它们上面似乎有一个彩色层)。

另外,输入文字现在是黑色的,我也希望它是白色的。

总而言之,我想修改以下属性。
1.textField背景色
2. textFiled占位符文本颜色
3. textFiled文本颜色
4.textFiled字体

有人知道怎么做吗?

在 viewDidAppear 中添加以下代码:

            let placeholderString = NSAttributedString(string: "Placeholder", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])
field.attributedPlaceholder = placeholderString

let iconView = field.leftView as! UIImageView
iconView.image = iconView.image?.withRenderingMode(.alwaysTemplate)
iconView.tintColor = .white

更新数据:
将这些设置放在 ViewDidAppear() 中确实解决了我的部分问题。
但是当我设置栏的背景颜色时,文本字段的背景颜色发生了变化。
因为 searchBar.barTintColor = .red 在 iOS11 的导航项中嵌入的 UISearchController 中不起作用,所以我使用了 searchBar.backgroundColor = .red
这让我很困惑。
那么如何分别改变searchBar的背景和textField的背景呢?

最佳答案

为搜索栏的文本字段设置attributedPlaceholder

@IBOutlet weak var sbSearchBar: UISearchBar!
if let textfield = sbSearchBar.value(forKey: "searchField") as? UITextField {

textfield.backgroundColor = UIColor.red
textfield.attributedPlaceholder = NSAttributedString(string: textfield.placeholder ?? "", attributes: [NSAttributedStringKey.foregroundColor : UIColor.white])

if let leftView = textfield.leftView as? UIImageView {
leftView.image = leftView.image?.withRenderingMode(.alwaysTemplate)
leftView.tintColor = UIColor.white
}

}

结果如下:

enter image description here

更新:

我想,这可能对你有帮助:how to change uitextfield color in searchcontroller?

只需在此代码中应用您的颜色组合即可查看。

if #available(iOS 11.0, *) {
let sc = UISearchController(searchResultsController: nil)
sc.delegate = self
let scb = sc.searchBar
scb.tintColor = UIColor.white
scb.barTintColor = UIColor.white


if let textfield = scb.value(forKey: "searchField") as? UITextField {
//textfield.textColor = // Set text color
if let backgroundview = textfield.subviews.first {

// Background color
backgroundview.backgroundColor = UIColor.white

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

}
}

if let navigationbar = self.navigationController?.navigationBar {
navigationbar.barTintColor = UIColor.blue
}
navigationItem.searchController = sc
navigationItem.hidesSearchBarWhenScrolling = false

}

结果:

enter image description here

关于ios - 如何在 UISearchController 中自定义 searchBar?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49292352/

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