我希望我的搜索栏的色调颜色是白色,这意味着取消按钮是白色的。当色调颜色为白色时,光标不可见。有没有一种方法可以单独设置光标颜色?
我希望我的搜索栏的色调颜色是白色,这意味着取消按钮是白色的。当色调颜色为白色时,光标不可见。有没有一种方法可以单独设置光标颜色?
将色调颜色设置为您想要的取消按钮颜色,然后使用UIAppearance协议将文本字段的色调颜色更改为您希望光标的颜色。例如:
[self.searchBar setTintColor:[UIColor whiteColor]];
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTintColor:[UIColor darkGrayColor]];
searchController.searchBar.tintColor = .white
UITextField.appearance(whenContainedInInstancesOf: [type(of: searchController.searchBar)]).tintColor = .black
请注意,searchBar不能是可选的。
如果你喜欢Swift中的功能强大但又烦人的一行代码,那么我将Benjamin的for循环简化为以下形式:
searchController.searchBar.tintColor = UIColor.whiteColor()
searchController.searchBar.subviews[0].subviews.flatMap(){ $0 as? UITextField }.first?.tintColor = UIColor.blueColor()
最简单的方法:使用 Swift 5:
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).tintColor = .black
使用for-where语法的简洁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中完成相同的操作,这是我在经历了很多麻烦后找到的解决方案:
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()
}
}
}
设置取消按钮和文本框不同的tintColor的最简单方法是使用以下代码:
[self.searchBar setTintColor:[UIColor whiteColor]];
[[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTintColor:UIColor.blueColor];
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)
}
}
}