【问题标题】:UISearchBar set different tint color for cancel buttonUISearchBar 为取消按钮设置不同的色调
【发布时间】:2016-04-12 16:12:47
【问题描述】:

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

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

【问题讨论】:

标签: swift uisearchbar


【解决方案1】:

我找到了解决方案:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 对不起,我没有测试过,但是我看到你已经用循环部分解决了,我忘了还有一层以上的子视图:)
    【解决方案3】:

    使用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
    

    【讨论】:

      猜你喜欢
      • 2014-10-23
      • 2011-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多