Last active
February 14, 2016 08:14
-
-
Save afshin-hoseini/0ddf313ca98da404904e to your computer and use it in GitHub Desktop.
A simple UISearchController with an activity indicator at search icon.
This file contains 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
// | |
// 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 | |
}) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Basically this class derived
UISearchController
and shows anUIActivityIndicator
instead the magnifier icon by setting theshowActivityIndicator
totrue
and vice versa, with alpha animation