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

后端 未结 12 1772
无人及你
无人及你 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 20:59

    Swift 4.2

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

    Base on Nick89's code , I changed like that for Swift 3.1

    let cancelButtonAttributes: [String: AnyObject] = [NSForegroundColorAttributeName: UIColor.white]
    
    UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes(cancelButtonAttributes, for: .normal)
    

    I want to change on UISearchBar only instead of all UIBarButton, so I'm using like UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self])

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

    did you try UISearchBar.appearance().tintColor = UIColor.whiteColor()

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

    The Swift 4.2 version, based on other answers:

    let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue): UIColor.orange]
    UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes(cancelButtonAttributes, for: .normal)
    
    0 讨论(0)
  • 2020-12-29 21:13

    Use this single line in code to change color of cancel button:

    UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes([NSAttributedStringKey(rawValue: NSAttributedStringKey.foregroundColor.rawValue): UIColor.white], for: .normal)
    

    Checked in Xcode 9.2 with Swift 4.0

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

    I know this question does have enough answers but here is simple way to achieve, SearchBar Background colour and Cancel button background colour we can change directly it in storyboard Attributes inspector.

    for SearchBar background colour

    for SearchBar cancel button colour

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