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

问题描述 投票:4回答:5

由于UISearchBar中的布局更改,旧版iOS的此问题的旧版本不再有效。

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

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

任何想法或建议?

谢谢!!

ios swift uisearchbar ios10
5个回答
10
投票
private func clearBackgroundColor() {
    guard let UISearchBarBackground: AnyClass = NSClassFromString("UISearchBarBackground") else { return }

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

这就是我最终所做的工作。谢谢大家的回答。


5
投票

我想你提到了搜索栏的BarTintColor

试试这个:

searchBar.barTintColor = .white

2
投票

试试这个。

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

2
投票

尝试设置背景图片:qazxsw poi


0
投票

只需在Interface Builder或代码中将搜索栏样式设置为[searchBar setBackgroundImage:[UIImage new]];,背景就会变得透明。

.Minimal

© www.soinside.com 2019 - 2024. All rights reserved.