Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: UIActivityIndicator in UISearchBar

Is it possible to display an UIActivityIndicator in the UISearchBar while searching?

like image 778
filou Avatar asked Nov 07 '12 18:11

filou


1 Answers

Found none of the advertised solutions worked well for iOS13... here is my own, which subclasses the Search Bar and should be more robust for future use

class SearchBar: UISearchBar {

    var activityIndicator: UIActivityIndicatorView?
    
    var isLoading: Bool {
        get {
            return activityIndicator != nil
        } set {
            if newValue {
                if activityIndicator == nil {
                    
                    guard let leftView = searchTextField.leftView else {
                        return
                    }
                    
                    let ai = UIActivityIndicatorView(style: .medium)
                    ai.frame = self.convert(leftView.frame, from: leftView.superview)
                    self.addSubview(ai)
                    
                    ai.startAnimating()
                    leftView.isHidden = true
                    activityIndicator = ai
                    
                }
            } else {
                activityIndicator?.removeFromSuperview()
                activityIndicator = nil
                
                guard let leftView = searchTextField.leftView else {
                    return
                }
                leftView.isHidden = false
            }
        }
    }
    
}
like image 135
Peter Lapisu Avatar answered Oct 04 '22 19:10

Peter Lapisu