我如何改变 UISearchBar
的文本颜色?
您可以通过访问searchBar内部的UITextField来完成此操作,然后您可以更改其背景颜色、文本颜色和所有其他UITextField属性。
添加以下扩展以访问textField:
extension UISearchBar {
/// Return text field inside a search bar
var textField: UITextField? {
let subViews = subviews.flatMap { $0.subviews }
guard let textField = (subViews.filter { $0 is UITextField }).first as? UITextField else { return nil
}
return textField
}
}
这对我有用。
if #available(iOS 13.0, *) {
searchBar.searchTextField.textColor = .white
}
Swift 5.2和iOS 13.3.1:-
它可以良好地运行。
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
(此解决方案仅适用于Xcode 10和iOS 12。)添加扩展以访问搜索栏的文本字段:
extension UISearchBar {
var textField: UITextField? {
return subviews.first?.subviews.compactMap { $0 as? UITextField }.first
}
}
let searchBar = UISearchBar()
searchBar.textField?.textColor = UIColor.white // or whichever color you want
// 编辑
上述代码在iOS 13上无法正常工作。更好的处理方法是使用:
extension UISearchBar {
var textField: UITextField? {
return self.subviews(ofType: UITextField.self).first
}
}
extension UIView {
var recursiveSubviews: [UIView] {
return self.subviews + self.subviews.flatMap { $0.recursiveSubviews }
}
func subviews<T: UIView>(ofType: T.Type) -> [T] {
return self.recursiveSubviews.compactMap { $0 as? T }
}
}
yourSearchBar.searchTextField.textColor = .yourColor
var tf = searchBar.AllSubViews().FirstOrDefault(v => v is UITextField);
if (tf != null)
(tf as UITextField).TextColor = UIColor.White;
public static IEnumerable<UIView> AllSubViews(this UIView view)
{
foreach (var v in view.Subviews)
{
yield return v;
foreach (var sv in v.AllSubViews())
{
yield return sv;
}
}
}
//试试这个家伙
yourSearchbar.searchTextField.textColor = .white
在我的情况下,解决方案是
id appearance = [UITextField appearanceWhenContainedInInstancesOfClasses:@[UISearchBar.class, BCRSidebarController.class]];
[appearance setTextColor:[UIColor.whiteColor colorWithAlphaComponent:0.56]];
Swift 5:
searchBar[keyPath: \.searchTextField].textColor = UIColor(...)
Swift 5:
searchBar [keyPath:\.searchTextField] .textColor = UIColor(...)
let searchBar = UISearchBar()
searchBar.searchTextField.textColor = .white
@IBOutlet weak var searchBar: UISearchBar!
searchBar.searchTextField.textColor = .white