我希望我的searchBar的色调颜色为白色(意味着取消按钮为白色)。当着色颜色为白色时,光标不可见。有没有办法分别设置光标颜色?
将您的色调颜色设置为您想要取消按钮的颜色,然后使用UIAppearance Protocol将文本字段上的色调颜色更改为您希望光标的颜色。例如:
[self.searchBar setTintColor:[UIColor whiteColor]];
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTintColor:[UIColor darkGrayColor]];
这是最简单的解决方案。
let textField = self.searchBar.value(forKey: "searchField") as! UITextField
textField.tintColor = UIColor.white
最简单的Swift 5:
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).tintColor = .black
这是Felipe的答案的“功能”版本(Swift 4.2)
// Make SearchBar's tint color white to get white cancel button.
searchBar.tintColor = .white
// Get the TextField subviews, change tint color to something else.
if let textFields = searchBar.subviews.first?.subviews.compactMap({ $0 as? UITextField }) {
textFields.forEach { $0.tintColor = UIColor.darkGray }
}
如果你喜欢斯威夫特的功能性但令人讨厌的单行,那么我就把Benjamin的循环归结为:
searchController.searchBar.tintColor = UIColor.whiteColor()
searchController.searchBar.subviews[0].subviews.flatMap(){ $0 as? UITextField }.first?.tintColor = UIColor.blueColor()
searchController.searchBar.tintColor = .white
UITextField.appearance(whenContainedInInstancesOf: [type(of: searchController.searchBar)]).tintColor = .black
请注意,searchBar不能是可选的。
使用for-where语法的Compact Swift 2.0解决方案(无需中断循环):
// Make SearchBar's tint color white to get white cancel button.
searchBar.tintColor = UIColor.white()
// Loop into it's subviews and find TextField, change tint color to something else.
for subView in searchBar.subviews[0].subviews where subView.isKindOfClass(UITextField) {
subView.tintColor = UIColor.darkTextColor()
}
这对我来说似乎也很快。
searchController.searchBar.tintColor = UIColor.whiteColor()
UITextField.appearanceWhenContainedInInstancesOfClasses([searchController.searchBar.dynamicType]).tintColor = UIColor.blackColor()
对于那些希望在Swift中做同样事情的人来说,这是一个解决方案,我在遇到很多麻烦之后来到了accros:
override func viewWillAppear(animated: Bool) {
self.searchBar.tintColor = UIColor.whiteColor()
let view: UIView = self.searchBar.subviews[0] as! UIView
let subViewsArray = view.subviews
for (subView: UIView) in subViewsArray as! [UIView] {
println(subView)
if subView.isKindOfClass(UITextField){
subView.tintColor = UIColor.blueColor()
}
}
}
我只想使用以下代码为UISearchBar添加扩展。
extension UISearchBar {
var cursorColor: UIColor! {
set {
for subView in self.subviews[0].subviews where ((subView as? UITextField) != nil) {
subView.tintColor = newValue
}
}
get {
for subView in self.subviews[0].subviews where ((subView as? UITextField) != nil) {
return subView.tintColor
}
// Return default tintColor
return UIColor.eightBit(red: 1, green: 122, blue: 255, alpha: 100)
}
}
}
为取消按钮和textField设置tintColor的最简单方法,使用:
self.searchBar setTintColor:[UIColor whiteColor]];
[[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTintColor:UIColor.blueColor];