UISearchBar为取消按钮设置不同的色调颜色

时间:2016-04-12 16:12:48

标签: swift uisearchbar

在我的swift应用程序中,我有一个像这样的搜索栏:

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()

如何为取消按钮设置另一种色调颜色作为整个搜索栏的色调?

3 个答案:

答案 0 :(得分:6)

我找到了解决方案:

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()
       }
   }

答案 1 :(得分:1)

为此,您必须访问按钮子视图,然后更改其颜色,您可以这样做:

  for subview in searchBar.subviews {
            if subview is UIButton { //checking if it is a button
                subview.tintColor = UIColor.greenColor()
            }
        }

答案 2 :(得分:1)

使用keyPath:

在连接到searchController时访问它-

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

当不是-

let cancelButton = searchBar.value(forKeyPath: "cancelButton") as? UIButton
cancelButton?.tintColor = UIColor.red