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

3
在我的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()

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

我在这个问题的回答中发布了一个答案:https://dev59.com/G2Ei5IYBdhLWcg3wPadh#42444940 - Derek Soike
3个回答

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
要做到这一点,您需要访问按钮子视图,然后更改其颜色,可以像这样操作:
  for subview in searchBar.subviews {
            if subview is UIButton { //checking if it is a button
                subview.tintColor = UIColor.greenColor()
            }
        }

抱歉我没有测试过,但是我看到你已经使用了循环部分解决了它,我忘记了有多个子视图层:) - Eric

1

使用keyPath:

当连接到搜索控制器时访问它-

// 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接