如何清除iOS10 Swift中的UISearchBar背景色?

问题描述:

由于UISearchBar中的布局更改,此旧版本的iOS的旧版本不再有效。如何清除iOS10 Swift中的UISearchBar背景色?

我已经尝试完全删除UISearchBar的背景颜色,但它不起作用。 (我试图查找它的层次结构视图,但xCode不断为此选项崩溃。)

private func clearBackgroundColor() { 
    for view in self.subviews { 
     view.backgroundColor = UIColor.clear 
     for subview in view.subviews { 
      subview.backgroundColor = UIColor.clear 
     } 
    } 
} 

任何想法或建议吗?

谢谢!

+0

你调用'ViewDidLayoutSubviews()'这个功能呢? – Lumialxk

+0

@Lumialxk Nah,UISearchBar没有这个方法。我从初始化中调用它。 – RainCast

private func clearBackgroundColor() { 
    guard let UISearchBarBackground: AnyClass = NSClassFromString("UISearchBarBackground") else { return } 

    for view in self.subviews { 
     for subview in view.subviews { 
      if subview.isKind(of: UISearchBarBackground) { 
       subview.alpha = 0 
      } 
     } 
    } 
} 

这是我在工作的最后还是没买。谢谢你的回答。

+0

就像是对未来流浪者的评论......这对Xcode 9,Swift 3.0(尚未与4.0一起工作过,不想破坏我的产品代码)** @ Lumialxk **的回答无效。 – QuantumHoneybees

+0

@QuantumHoneybees for iOS 11您需要在内容视图中迭代。 'searchBar.subviews.first?.subviews'而不是'searchBar.subviews' – btype

我觉得你提的关于搜索栏

的BarTintColor试试这个:

searchBar.barTintColor = .white 
+2

谢谢。但事情是我需要的是将其设置为UIColor.clear。在我将其设置为清除后,它实际上在屏幕上显示为黑色。我需要这个搜索栏中的所有东西都有一个透明的颜色,只有文本输入除外。 – RainCast

+1

UIColor.clear显示searchBar后面视图的颜色。所以我认为searchBar的backgounrd颜色背后的视图是黑色的 –

试试这个。

class CustomSearchBar: UISearchBar { 
    override func layoutSubviews() { 
     super.layoutSubviews() 
     clearBackgroundColor() // function in the question 
    } 
} 

private func clearBackgroundColor() { 
    for view in self.subviews { 
     view.backgroundColor = UIColor.clear 
     for subview in view.subviews { 
      subview.backgroundColor = UIColor.clear 
     } 
    } 
} 
+0

谢谢,我的xCode“View Hierarchy”函数工作后我又转向另一个方向,基本上检查了布局中的所有名称。 – RainCast

尝试设置背景图片: [searchBar setBackgroundImage:[UIImage new]];