UISearchBar

1. Changing cursor color on UISearchBar without changing tintColor

I want my searchBar's tint color to be white (meaning the cancel button be white). The cursor is not visible when the tint color is white. Is there a way to set cursor color separately?

Set your tint color to the color you want the cancel button to be and then use the UIAppearance Protocol to change the tint color on the text field to be the color you wish the cursor to be. Ex:

[self.searchBar setTintColor:[UIColor whiteColor]];                
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] 
setTintColor:[UIColor darkGrayColor]];

这种可以实现需要的效果,但是有可能所有的UITextField都发生了改变,还有一些其他回答者方案可以参考,大致的思路是遍历UISearchBar子视图,拿到UITextField

searchController.searchBar.tintColor = UIColor.whiteColor()

searchController.searchBar.subviews[0].subviews.flatMap(){ $0 as? UITextField }.first?.tintColor = UIColor.blueColor()
// 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()
}

你可能感兴趣的:(UISearchBar)