Skip to content

Instantly share code, notes, and snippets.

@afshin-hoseini
Last active February 14, 2016 08:14
Show Gist options
  • Save afshin-hoseini/0ddf313ca98da404904e to your computer and use it in GitHub Desktop.
Save afshin-hoseini/0ddf313ca98da404904e to your computer and use it in GitHub Desktop.
A simple UISearchController with an activity indicator at search icon.
//
// UISearchControllerWithIndicator.swift
//
// Created by Afshin Hoseini on 2/10/16.
// https://github.com/afshin-hoseini
//
import Foundation
import UIKit
class UISearchControllerWithIndicator: UISearchController {
private var didPutActivityIndicator = false
private var searchTextField: UIView? = nil
private var activityIndicator: UIActivityIndicatorView? = nil
private var searchIcon: UIImageView? = nil
private func putActivityIndicator() {
guard !didPutActivityIndicator else { return }
let containerView = self.searchBar.subviews[0]
activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
activityIndicator!.frame = CGRectMake(0, 0, 0, 0)
//Inserts activity indicator inside the UISearchTextField
for var i=0; i < containerView.subviews.count; i++ {
let view = containerView.subviews[i]
if view is UITextField {
for v in view.subviews {
if v is UIImageView {
searchIcon = v as? UIImageView
}
searchTextField = view
view.addSubview(activityIndicator!)
didPutActivityIndicator = true
}
break
}
}
}
var showActivityIndicator: Bool = false {
didSet {
putActivityIndicator()
if showActivityIndicator {
activityIndicator?.startAnimating()
self.activityIndicator!.frame = CGRectMake(self.searchIcon!.frame.origin.x, self.searchIcon!.frame.origin.y, self.searchIcon!.frame.size.width, self.searchIcon!.frame.size.height)
self.activityIndicator?.alpha = 0
self.searchIcon?.alpha = 1
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.activityIndicator?.alpha = 1
self.searchIcon?.alpha = 0
})
}
else {
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.activityIndicator?.alpha = 0
self.searchIcon?.alpha = 1
})
}
}
}
}
@afshin-hoseini
Copy link
Author

Basically this class derived UISearchController and shows an UIActivityIndicator instead the magnifier icon by setting the showActivityIndicator to true and vice versa, with alpha animation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment