How to change the colour of the 'Cancel' button on the UISearchBar in Swift

后端 未结 12 1773
无人及你
无人及你 2020-12-29 20:28

I have added a UISearchBar to the top of my PFQueryTableViewController. I have changed the colour of the searchBar to be the colour of my app, but

相关标签:
12条回答
  • 2020-12-29 21:13

    Swift 5

    UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes([.foregroundColor : UIColor.barTint], for: .normal)
    
    0 讨论(0)
  • 2020-12-29 21:14

    Swift 4.2, 4.1

    A custom class added here can be used to customize the most common elements in a searchBar. Custom class SearchBar can result in to the following search bar.

    0 讨论(0)
  • 2020-12-29 21:15

    Having a look around, this seemed to be the best way to achieve what I needed:

     let cancelButtonAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
     UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes , for: .normal)
    
    0 讨论(0)
  • 2020-12-29 21:17

    You can simply set tintcolor of searchBar to change color of Cancel button. This is available since swift 4 so should do the trick.

    let searchBar = UISearchBar(frame: )
    searchBar.tintColor = .orange
    

    Search bar cancel button and cursor color change

    0 讨论(0)
  • 2020-12-29 21:18

    With the Swift 4.0 RELEASE 2017-09-19 toolchain, this worked:

        let cancelButtonAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
        UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes(cancelButtonAttributes, for: .normal)
    
    0 讨论(0)
  • 2020-12-29 21:25

    All the above answers didn't work for me. (Got 'Type 'NSAttributedString.Key' (aka 'NSString') has no member 'foregroundColor'' error)

    Maybe because I'm at Swift 3...

    Here's the slightly-modified code that worked for me:-

    UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes([NSForegroundColorAttributeName : .black], for: .normal)
    

    Note:-

    If you are using UISearchController, insert this code to 'willPresentSearchController:' or 'didPresentSearchController:'

    0 讨论(0)
提交回复
热议问题