更改UISearchBar上的光标颜色而不更改tintColor
我想我的searchBar的色调是白色的(这意味着取消button是白色的)。 当色调为白色时,光标不可见。 有没有办法分别设置光标颜色?
将您的色调颜色设置为您想要取消button的颜色,然后使用UIAppearance Protocol将文本字段上的色调更改为希望光标所在的颜色。 例如:
[self.searchBar setTintColor:[UIColor whiteColor]]; [[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTintColor:[UIColor darkGrayColor]];
如果你喜欢Swift中function强大而又烦人的单人游戏,那么本杰明就可以循环下去:
searchController.searchBar.tintColor = UIColor.whiteColor() searchController.searchBar.subviews[0].subviews.flatMap(){ $0 as? UITextField }.first?.tintColor = UIColor.blueColor()
Compact Swift 2.0解决scheme,使用for-where语法(不需要中断循环):
// 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() }
对于那些希望在Swift中做同样的事情的人来说,这是我经历了很多麻烦之后才提出来的一个解决scheme:
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() } } }
searchBar.tintColor = [UIColor whiteColor]; searchBar.backgroundColor = [UIColor clearColor]; for ( UIView *v in [searchBar.subviews.firstObject subviews] ) { if ( YES == [v isKindOfClass:[UITextField class]] ) { [((UITextField*)v) setTintColor:[UIColor blueColor]]; break; } }
这似乎也很快适用于我。
searchController.searchBar.tintColor = UIColor.whiteColor() UITextField.appearanceWhenContainedInInstancesOfClasses([searchController.searchBar.dynamicType]).tintColor = UIColor.blackColor()
我只是用下面的代码添加一个扩展到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) } } }
这是最简单的解决scheme。
let textField = self.searchBar.value(forKey: "searchField") as! UITextField textField.tintColor = UIColor.white
Swift 3.0版本
searchController.searchBar.tintColor = .white UITextField.appearance(whenContainedInInstancesOf: [type(of: searchController.searchBar)]).tintColor = .black
iOS 9及以上版本
最简单的方法来设置一个tintColor不同的取消button和textField,使用这个:
self.searchBar setTintColor:[UIColor whiteColor]]; [[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTintColor:UIColor.blueColor];