在UISearchBar上更改光标颜色而不更换TintColor
-
20-12-2019 - |
题
我希望我的搜索栏的色调颜色为白色(意味着取消按钮是白色的)。当色调为白色时,光标不可见。有没有办法分别设置光标颜色?
解决方案
将颜色设置为要取消按钮的颜色,然后使用 UIAppearance协议更改文本字段上的色调颜色为您希望光标的颜色。前:
[self.searchBar setTintColor:[UIColor whiteColor]];
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTintColor:[UIColor darkGrayColor]];
. 其他提示
如果你喜欢功能,但令人讨厌的单行队员在Swift中,我有enjamin的循环到这个:
searchController.searchBar.tintColor = UIColor.whiteColor()
searchController.searchBar.subviews[0].subviews.flatMap(){ $0 as? UITextField }.first?.tintColor = UIColor.blueColor()
. swift 3.0和4版本
searchController.searchBar.tintColor = .white
UITextField.appearance(whenContainedInInstancesOf: [type(of: searchController.searchBar)]).tintColor = .black
.
请注意,搜索栏不能是可选的。
Compact Swift 2.0解决方案使用 for-其中语法(无需断开循环):
// 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)
}
}
}
. IOS 9及更高版本
为取消按钮和文本域设置TintColor的最简单方法,使用以下方式:
[self.searchBar setTintColor:[UIColor whiteColor]];
[[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTintColor:UIColor.blueColor];
. 这是最简单的解决方案。
let textField = self.searchBar.value(forKey: "searchField") as! UITextField
textField.tintColor = UIColor.white
. 在swift 5中最简单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 }
}
. 不隶属于 StackOverflow