Created
August 27, 2018 16:53
-
-
Save andru255/ebf9a625357cafb763c68ee5fca70dc2 to your computer and use it in GitHub Desktop.
UISearchBar with UIActivityIndicator source: https://stackoverflow.com/a/45905342
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
extension UISearchBar { | |
public var textField: UITextField? { | |
let subViews = subviews.flatMap { $0.subviews } | |
guard let textField = subViews.first(where: { $0 is UITextField }) as? UITextField else { | |
return nil | |
} | |
return textField | |
} | |
public var activityIndicator: UIActivityIndicatorView? { | |
return textField?.leftView?.subviews.compactMap { $0 as? UIActivityIndicatorView }.first | |
} | |
var isLoading: Bool { | |
get { | |
return activityIndicator != nil | |
} | |
set { | |
if newValue { | |
if activityIndicator == nil { | |
let newActivityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray) | |
newActivityIndicator.transform = CGAffineTransform(scaleX: 0.7, y: 0.7) | |
newActivityIndicator.startAnimating() | |
newActivityIndicator.backgroundColor = UIColor.white | |
textField?.leftView?.addSubview(newActivityIndicator) | |
let leftViewSize = textField?.leftView?.frame.size ?? CGSize.zero | |
newActivityIndicator.center = CGPoint(x: leftViewSize.width / 2, y: leftViewSize.height / 2) | |
} | |
} else { | |
activityIndicator?.removeFromSuperview() | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment