3

In my swift app I have a search bar like this:

lazy var searchBar = UISearchBar(frame: CGRectMake(0, 0, 0, 0))
searchBar.delegate = self
searchBar.showsCancelButton = true
searchBar.tintColor = UIColor.blackColor()
searchBar.spellCheckingType = .No
searchBar.autocapitalizationType = .None
searchBar.autocorrectionType = .No
searchBar.placeholder = "Suchbegriff eingeben ..."
searchBar.sizeToFit()

How can I set another tint color for cancel button as the tint color for the whole search bar?

kye
  • 2,166
  • 3
  • 27
  • 41
Stack108
  • 915
  • 2
  • 14
  • 35

3 Answers3

6

i found the solution:

let view: UIView = self.searchBar.subviews[0] as UIView
let subViewsArray = view.subviews

   for subView: UIView in subViewsArray {
       if subView.isKindOfClass(UITextField){
          subView.tintColor = UIColor.blackColor()
       }
   }
Stack108
  • 915
  • 2
  • 14
  • 35
1

To do this, you have to access the button subview, and then change its color, you can do that like this:

  for subview in searchBar.subviews {
            if subview is UIButton { //checking if it is a button
                subview.tintColor = UIColor.greenColor()
            }
        }
Eric
  • 1,210
  • 8
  • 25
  • Sorry I hadn't tested it, but I see you have solved it using the loop part, I had forgotten that there was more then one layer of subviews:) – Eric Apr 13 '16 at 12:48
1

use the keyPath:

when accessing it when hooked up to a searchController-

// this is what worked for me
let cancelButton = searchController.searchBar.value(forKeyPath: "cancelButton") as? UIButton
cancelButton?.tintColor = UIColor.red

when not-

let cancelButton = searchBar.value(forKeyPath: "cancelButton") as? UIButton
cancelButton?.tintColor = UIColor.red
Lance Samaria
  • 17,576
  • 18
  • 108
  • 256