Make UISearchBar background clear

后端 未结 17 1133
野的像风
野的像风 2021-01-07 17:17

I am not able to clear search bar I have tried to make it clear by setting its background color clear and I have also placed one image under searchbar

I have also ma

17条回答
  •  执念已碎
    2021-01-07 17:31

    I tried @Johnson's answer however it didn't work well for me. (iOS 13, swift 5)

    However the logic behind the solution seemed well. So tried to iterate all subviews of the searchBar and it worked!

    I hope, it will help :)


    Solution also worked for me in iOS 12.4 - swift 5

    Remove Background Method

    private func removeBackground(from searchBar: UISearchBar) {
        guard let BackgroundType = NSClassFromString("_UISearchBarSearchFieldBackgroundView") else { return }
    
        for v in searchBar.allSubViewsOf(type: UIView.self) where v.isKind(of: BackgroundType){
            v.removeFromSuperview()
        }
    }
    

    Helper Methods -> UIViewExtension

    extension UIView {
    
        public func allSubViewsOf(type : T.Type) -> [T]{
            var all = [T]()
            func getSubview(view: UIView) {
                if let wrapped = view as? T, wrapped != self{
                    all.append(wrapped)
                }
                guard view.subviews.count>0 else { return }
                view.subviews.forEach{ getSubview(view: $0) }
            }
            getSubview(view: self)
            return all
        }
    }
    

提交回复
热议问题