How to handle selection when using GMSAutocompleteFetcher in iOS? - ios

I have google place autocomplete which display an GMSAutocompleteFetcher. the code is come from Google developer website but the problem is I can't find a way how to handle selection right after user seeing the words appear on the textView to display it as place ID, so far this is my code:
import UIKit
import GoogleMaps
class FetcherSampleViewController: UIViewController {
var textField: UITextField?
var resultText: UITextView?
var fetcher: GMSAutocompleteFetcher?
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: "handletap:")
self.view.backgroundColor = UIColor.whiteColor()
self.edgesForExtendedLayout = .None
// Set bounds to inner-west Sydney Australia.
let neBoundsCorner = CLLocationCoordinate2D(latitude: -33.843366,
longitude: 151.134002)
let swBoundsCorner = CLLocationCoordinate2D(latitude: -33.875725,
longitude: 151.200349)
let bounds = GMSCoordinateBounds(coordinate: neBoundsCorner,
coordinate: swBoundsCorner)
// Set up the autocomplete filter.
let filter = GMSAutocompleteFilter()
filter.type = .Establishment
// Create the fetcher.
fetcher = GMSAutocompleteFetcher(bounds: bounds, filter: filter)
fetcher?.delegate = self
textField = UITextField(frame: CGRect(x: 5.0, y: 0,
width: self.view.bounds.size.width - 5.0, height: 44.0))
textField?.autoresizingMask = .FlexibleWidth
textField?.addTarget(self, action: "textFieldDidChange:",
forControlEvents: .EditingChanged)
resultText = UITextView(frame: CGRect(x: 0, y: 45.0,
width: self.view.bounds.size.width,
height: self.view.bounds.size.height - 45.0))
resultText?.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
resultText?.text = "No Results"
resultText?.editable = false
resultText?.addGestureRecognizer(tap)
self.view.addSubview(textField!)
self.view.addSubview(resultText!)
}
func textFieldDidChange(textField: UITextField) {
fetcher?.sourceTextHasChanged(textField.text!)
}
func handletap (sender: UITapGestureRecognizer){
print("I dont know what to do here")
}
}
extension FetcherSampleViewController: GMSAutocompleteFetcherDelegate {
func didAutocompleteWithPredictions(predictions: [GMSAutocompletePrediction]) {
let resultsStr = NSMutableAttributedString()
for prediction in predictions {
resultsStr.appendAttributedString(prediction.attributedPrimaryText)
resultsStr.appendAttributedString(NSAttributedString(string: "\n"))
}
resultText?.attributedText = resultsStr
}
func didFailAutocompleteWithError(error: NSError) {
resultText?.text = error.localizedDescription
}
}
I use UITapGestureRecognizer but I don't know what should I do. If you can help me I would appreciate it :)

Since all the predictions are just newline-delimited rows in a text field, it's going to be difficult to tell which of them the user tapped on.
How about instead of a UITextView, you use a UITableView and have one row per prediction. This will make it easy to detect which prediction was selected.

Related

After a graph from "Charts by Daniel Cohen Gindi" graphs itself, a UIButton on the screen is no longer selectable

I am using the open-sourced Charts by Daniel Cohen Gindi: https://github.com/danielgindi/Charts
I have a pie chart on my screen which graphs itself like this:
//set pie chart data
graphView.data = PieChartData(dataSets: iPieChartDataSet)
Additionally I have a button on the screen which displays a popover similarly to the accepted answer of this question.
"What I Want"
When the user presses the UIButton on the screen, I want a popover to display.
"What works"
When I press the UIButton, the popover is created and presented as expected. Additionally I can create the popover, close it, and recreate it.
"What doesn't work"
If the graph is present on the screen, then the popover does not appear. I tried to using a print statement within the UIButton and it looks like the IBAction is never fired.
Other information
Other UI actions work. I can tab to other tabs and I can swivel the graph around. It just seems that the UIButton is somehow getting turned off if the graph on the screen is present.
Relevant code:
How the popover is being created:
#IBAction func informationButtonTapped(_ sender: UIButton) {
var popoverContent = (self.storyboard?.instantiateViewController(withIdentifier: segueIdentifiers.informationPopover))! as UIViewController
var nav = UINavigationController(rootViewController: popoverContent)
nav.modalPresentationStyle = UIModalPresentationStyle.popover
var popover = nav.popoverPresentationController
popoverContent.preferredContentSize = CGSize(width: 500,height: 600)
popover?.delegate = self
popover?.sourceView = self.view
popover?.sourceRect = CGRect(x: 0, y: 0, width: 100, height: 100)
self.present(nav, animated: true, completion: nil)
}
How the graph is being created (shortened as much as possible):
private func setChart(dataPoints: [String?], values: [Double]) {
var dataEntries: [PieChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = PieChartDataEntry(value: values[i], label: dataPoints[i])
dataEntries.append(dataEntry)
}
let pieChartDataSet = PieChartDataSet(values: dataEntries, label: "")
var iPieChartDataSet: [IChartDataSet] = []
iPieChartDataSet.append(pieChartDataSet)
graphView.animate(xAxisDuration: 1.0, yAxisDuration: 1.0)
graphView.layer.borderWidth = 0.1
//set pie chart data
graphView.data = PieChartData(dataSets: iPieChartDataSet)
}
For my app I created the buttons programmatically, and I've had no issues so far. Heres my button code, see if it works for you.
var updateButton : UIButton = UIButton(type: .custom)
override func viewDidLoad() {
super.viewDidLoad()
setChart()
let buttonHeight = 60.0
let buttonWidth = 280.0
let xspacing = 45.0
let fontSize:CGFloat = 30
let buttonColor = UIColor.black
let textColor = UIColor.blue
updateButton.frame = CGRect(x: xspacing, y: 400, width: buttonWidth, height: buttonHeight)
updateButton.backgroundColor = buttonColor
updateButton.clipsToBounds = true
updateButton.setTitle("Update", for: .normal)
updateButton.titleLabel!.font = UIFont(name: "ScienceFair", size: fontSize)
updateButton.titleLabel!.textColor = UIColor.black
updateButton.addTarget(self, action: #selector(updateFunc), for: .touchUpInside)
view.addSubview(updateButton)
}
func updateFunc() {
UIView.animate(withDuration: 0.1, animations: { self.updateButton.transform = CGAffineTransform(scaleX: 0.9, y: 0.9) }, completion: { (finish: Bool) in UIView.animate(withDuration: 0.1, animations: { self.updateButton.transform = CGAffineTransform.identity }) })
//Present Popover
}
Ignore stackoverflow formatting for the commented #selector. Its not a comment.

Google place autocomplete in swift doesn't works perfectly

I tried to make "place autocomplete" from google place and I copy paste the codes directly from the website here google developer and I already set the api key too but the problem is why the results look so odd when I typing a place as you can see on the picture it seems works but not perfect. here is my code:
import UIKit
import GoogleMaps
class FetcherSampleViewController: UIViewController {
var textField: UITextField?
var resultText: UITextView?
var fetcher: GMSAutocompleteFetcher?
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
self.edgesForExtendedLayout = .None
// Set bounds to inner-west Sydney Australia.
let neBoundsCorner = CLLocationCoordinate2D(latitude: -33.843366,
longitude: 151.134002)
let swBoundsCorner = CLLocationCoordinate2D(latitude: -33.875725,
longitude: 151.200349)
let bounds = GMSCoordinateBounds(coordinate: neBoundsCorner,
coordinate: swBoundsCorner)
// Set up the autocomplete filter.
let filter = GMSAutocompleteFilter()
filter.type = .Establishment
// Create the fetcher.
fetcher = GMSAutocompleteFetcher(bounds: bounds, filter: filter)
fetcher?.delegate = self
textField = UITextField(frame: CGRect(x: 5.0, y: 0,
width: self.view.bounds.size.width - 5.0, height: 44.0))
textField?.autoresizingMask = .FlexibleWidth
textField?.addTarget(self, action: "textFieldDidChange:",
forControlEvents: .EditingChanged)
resultText = UITextView(frame: CGRect(x: 0, y: 45.0,
width: self.view.bounds.size.width,
height: self.view.bounds.size.height - 45.0))
resultText?.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
resultText?.text = "No Results"
resultText?.editable = false
self.view.addSubview(textField!)
self.view.addSubview(resultText!)
}
func textFieldDidChange(textField: UITextField) {
fetcher?.sourceTextHasChanged(textField.text!)
}
}
extension FetcherSampleViewController: GMSAutocompleteFetcherDelegate {
func didAutocompleteWithPredictions(predictions: [GMSAutocompletePrediction]) {
let resultsStr = NSMutableString()
for prediction in predictions {
resultsStr.appendFormat("%#\n", prediction.attributedPrimaryText)
}
resultText?.text = resultsStr as String
}
func didFailAutocompleteWithError(error: NSError) {
resultText?.text = error.localizedDescription
}
}
can anyone help me?
This is because prediction.attributedPrimaryText is an attributed string. Try the following code
func didAutocompleteWithPredictions(predictions: [GMSAutocompletePrediction]) {
let resultsStr = NSMutableAttributedString()
for prediction in predictions {
resultsStr.appendAttributedString(prediction.attributedPrimaryText)
resultsStr.appendAttributedString(NSAttributedString(string: "\n"))
}
resultText?.attributedText = resultsStr
}

iOS Swift displaying character by character from a string array in UILabel.text [duplicate]

New to Swift 2.0; trying to learn it, interested in animation and tried to write some code to display a message on screen one character at a time.
I wrote this, it works, but I cannot help but could I not do something with CALayers perhaps and/or alpha values? Or some animate gizmo, something more swift worthy; this feels & looks kinda clunky, sort 1977 really.
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let supertext = "A long time ago, in a galaxy far, far away ..."
let round = supertext.characters.count
for i in 0...round {
let delay = Double(i)/10
let subtext = supertext[supertext.startIndex..<supertext.startIndex.advancedBy(i)]
NSTimer.scheduledTimerWithTimeInterval(delay, target: self, selector: "ghostText:", userInfo: ["theText" :subtext], repeats: false)
}
}
var view3:UITextView = UITextView()
func ghostText(timer:NSTimer) {
view3.removeFromSuperview()
let userInfo = timer.userInfo as! Dictionary<String, AnyObject>
let tempText:NSString = (userInfo["theText"] as! NSString)
print(tempText)
let font = UIFont(name: "Georgia", size: 18.0) ?? UIFont.systemFontOfSize(18.0)
let textFont = [NSFontAttributeName:font]
let subChararacter = NSAttributedString(string: String(tempText), attributes: textFont)
view3.frame = CGRect(x: 100, y: 120, width: CGRectGetWidth(self.view.frame), height: CGRectGetWidth(self.view.frame)-20)
view3.attributedText = subChararacter
self.view.addSubview(view3)
}
I suppose Swiftworthy is subjective, but here's another implementation based on how your code currently works that wraps the NSTimer in a Swift class.
class Timer {
typealias TimerFunction = (Int)->Bool
private var handler: TimerFunction
private var i = 0
init(interval: NSTimeInterval, handler: TimerFunction) {
self.handler = handler
NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: "timerFired:", userInfo: nil, repeats: true)
}
#objc
private func timerFired(timer:NSTimer) {
if !handler(i++) {
timer.invalidate()
}
}
}
class ViewController: UIViewController {
let text: NSAttributedString = {
let font = UIFont(name: "Georgia", size: 18.0) ?? UIFont.systemFontOfSize(18.0)
return NSAttributedString(string: "A long time ago, in a galaxy far, far away ...", attributes: [NSFontAttributeName: font])
}()
override func viewDidLoad() {
super.viewDidLoad()
let textView = UITextView(frame: CGRect(x: 100, y: 120, width: CGRectGetWidth(self.view.frame), height: CGRectGetWidth(self.view.frame)-20))
self.view.addSubview(textView)
let _ = Timer(interval: 0.1) {i -> Bool in
textView.attributedText = self.text.attributedSubstringFromRange(NSRange(location: 0, length: i+1))
return i + 1 < self.text.string.characters.count
}
}
}

Displaying text one character at a time in swift 2.0

New to Swift 2.0; trying to learn it, interested in animation and tried to write some code to display a message on screen one character at a time.
I wrote this, it works, but I cannot help but could I not do something with CALayers perhaps and/or alpha values? Or some animate gizmo, something more swift worthy; this feels & looks kinda clunky, sort 1977 really.
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let supertext = "A long time ago, in a galaxy far, far away ..."
let round = supertext.characters.count
for i in 0...round {
let delay = Double(i)/10
let subtext = supertext[supertext.startIndex..<supertext.startIndex.advancedBy(i)]
NSTimer.scheduledTimerWithTimeInterval(delay, target: self, selector: "ghostText:", userInfo: ["theText" :subtext], repeats: false)
}
}
var view3:UITextView = UITextView()
func ghostText(timer:NSTimer) {
view3.removeFromSuperview()
let userInfo = timer.userInfo as! Dictionary<String, AnyObject>
let tempText:NSString = (userInfo["theText"] as! NSString)
print(tempText)
let font = UIFont(name: "Georgia", size: 18.0) ?? UIFont.systemFontOfSize(18.0)
let textFont = [NSFontAttributeName:font]
let subChararacter = NSAttributedString(string: String(tempText), attributes: textFont)
view3.frame = CGRect(x: 100, y: 120, width: CGRectGetWidth(self.view.frame), height: CGRectGetWidth(self.view.frame)-20)
view3.attributedText = subChararacter
self.view.addSubview(view3)
}
I suppose Swiftworthy is subjective, but here's another implementation based on how your code currently works that wraps the NSTimer in a Swift class.
class Timer {
typealias TimerFunction = (Int)->Bool
private var handler: TimerFunction
private var i = 0
init(interval: NSTimeInterval, handler: TimerFunction) {
self.handler = handler
NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: "timerFired:", userInfo: nil, repeats: true)
}
#objc
private func timerFired(timer:NSTimer) {
if !handler(i++) {
timer.invalidate()
}
}
}
class ViewController: UIViewController {
let text: NSAttributedString = {
let font = UIFont(name: "Georgia", size: 18.0) ?? UIFont.systemFontOfSize(18.0)
return NSAttributedString(string: "A long time ago, in a galaxy far, far away ...", attributes: [NSFontAttributeName: font])
}()
override func viewDidLoad() {
super.viewDidLoad()
let textView = UITextView(frame: CGRect(x: 100, y: 120, width: CGRectGetWidth(self.view.frame), height: CGRectGetWidth(self.view.frame)-20))
self.view.addSubview(textView)
let _ = Timer(interval: 0.1) {i -> Bool in
textView.attributedText = self.text.attributedSubstringFromRange(NSRange(location: 0, length: i+1))
return i + 1 < self.text.string.characters.count
}
}
}

How to show activity indicator while tableView loads?

When I switch between my tabs it loads some seconds and I want to know that my data is loading. For that I decided to add an activity indicator.
I wrote a little function:
func showActivityIndicator() {
dispatch_async(dispatch_get_main_queue()) {
self.spinner = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge)
self.spinner.frame = CGRect(x: 0.0, y: 0.0, width: 80.0, height: 80.0)
self.spinner.center = CGPoint(x:self.loadingView.bounds.size.width / 2, y:self.loadingView.bounds.size.height / 2)
self.loadingView.addSubview(self.spinner)
self.view.addSubview(self.loadingView)
self.spinner.startAnimating()
}
}
that will show my indicator. And try to use it when I tapped from my infoController to button:
#IBAction func goToMainFromInfo(sender: AnyObject) {
self.showActivityIndicator()
self.performSegueWithIdentifier("fromMainToInfoWActivity", sender: nil)
self.hideActivityIndicator()
}
}
I show it before segue perform and hide after. It doesn't help me. When I did try to use sync:
#IBAction func goToMainFromInfo(sender: AnyObject) {
dispatch_async(dispatch_get_main_queue()) {
self.showActivityIndicator()
self.performSegueWithIdentifier("fromMainToInfoWActivity", sender: nil)
self.hideActivityIndicator()
}
}
But it doesn't help too. When I press to tab it opacity becomes 0.5 and I wait while it loading. But I do not see my activity indicator.
What is the problem?
Just try this:
var indicator = UIActivityIndicatorView()
func activityIndicator() {
indicator = UIActivityIndicatorView(frame: CGRectMake(0, 0, 40, 40))
indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
indicator.center = self.view.center
self.view.addSubview(indicator)
}
And where you want to start animating
indicator.startAnimating()
indicator.backgroundColor = UIColor.whiteColor()
For stop:
indicator.stopAnimating()
indicator.hidesWhenStopped = true
Note: Avoid the calling of start and stop at the same time. Just give some conditions.
SWIFT : 4.2
Just try this:
var indicator = UIActivityIndicatorView()
func activityIndicator() {
indicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
indicator.style = UIActivityIndicatorView.Style.gray
indicator.center = self.view.center
self.view.addSubview(indicator)
}
And where you want to start animating
activityIndicator()
indicator.startAnimating()
indicator.backgroundColor = .white
For stop:
indicator.stopAnimating()
indicator.hidesWhenStopped = true
Swift 3.0
// UIView Extension
fileprivate var ActivityIndicatorViewAssociativeKey = "ActivityIndicatorViewAssociativeKey"
public extension UIView {
var activityIndicatorView: UIActivityIndicatorView {
get {
if let activityIndicatorView = getAssociatedObject(&ActivityIndicatorViewAssociativeKey) as? UIActivityIndicatorView {
return activityIndicatorView
} else {
let activityIndicatorView = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
activityIndicatorView.activityIndicatorViewStyle = .gray
activityIndicatorView.color = .gray
activityIndicatorView.center = center
activityIndicatorView.hidesWhenStopped = true
addSubview(activityIndicatorView)
setAssociatedObject(activityIndicatorView, associativeKey: &ActivityIndicatorViewAssociativeKey, policy: .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return activityIndicatorView
}
}
set {
addSubview(newValue)
setAssociatedObject(newValue, associativeKey:&ActivityIndicatorViewAssociativeKey, policy: .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
// NSObject Extension
public extension NSObject {
func setAssociatedObject(_ value: AnyObject?, associativeKey: UnsafeRawPointer, policy: objc_AssociationPolicy) {
if let valueAsAnyObject = value {
objc_setAssociatedObject(self, associativeKey, valueAsAnyObject, policy)
}
}
func getAssociatedObject(_ associativeKey: UnsafeRawPointer) -> Any? {
guard let valueAsType = objc_getAssociatedObject(self, associativeKey) else {
return nil
}
return valueAsType
}
}
start animation
tableView.activityIndicatorView.startAnimating()
stop animation
tableView.activityIndicatorView.stopAnimating()
You can find more code in Magic
Swift 2+
class ViewController: UITableViewController {
weak var activityIndicatorView: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
let activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
tableView.backgroundView = activityIndicatorView
self.activityIndicatorView = activityIndicatorView
activityIndicatorView.startAnimating()
}
...
}
I use two extension methods to add an UIActivityIndicatorView as the backgroundView of the tableview.
extension UITableView {
func showActivityIndicator() {
DispatchQueue.main.async {
let activityView = UIActivityIndicatorView(style: .medium)
self.backgroundView = activityView
activityView.startAnimating()
}
}
func hideActivityIndicator() {
DispatchQueue.main.async {
self.backgroundView = nil
}
}
}
You can show/hide it like this.
tableView.showActivityIndicator()
tableView.hideActivityIndicator()
This code can help you :)
let indicator:UIActivityIndicatorView = UIActivityIndicatorView (activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
indicator.color = UIColor .magentaColor()
indicator.frame = CGRectMake(0.0, 0.0, 10.0, 10.0)
indicator.center = self.view.center
self.view.addSubview(indicator)
indicator.bringSubviewToFront(self.view)
indicator.startAnimating()
SWIFT
Place this below your class:
let indicator:UIActivityIndicatorView = UIActivityIndicatorView (activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
Place this in your loadView():
indicator.color = UIColor .magentaColor()
indicator.frame = CGRectMake(0.0, 0.0, 10.0, 10.0)
indicator.center = self.view.center
self.view.addSubview(indicator)
indicator.bringSubviewToFront(self.view)
indicator.startAnimating()
In my case, I am requesting json objects through a func request, so I placed this at the end of that function to remove the activity indicator once the data loads:
self.indicator.stopAnimating()
self.indicator.hidesWhenStopped = true
Another approach, In my code I added an extension for UITableView (Swift 2.3) :
extension UITableView {
func activityIndicator(center: CGPoint = CGPointZero, loadingInProgress: Bool) {
let tag = 12093
if loadingInProgress {
var indicator = UIActivityIndicatorView()
indicator = UIActivityIndicatorView(frame: CGRectMake(0, 0, 40, 40))
indicator.tag = tag
indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge
indicator.color = //Your color here
indicator.center = center
indicator.startAnimating()
indicator.hidesWhenStopped = true
self.superview?.addSubview(indicator)
}else {
if let indicator = self.superview?.viewWithTag(tag) as? UIActivityIndicatorView { {
indicator.stopAnimating()
indicator.removeFromSuperview()
}
}
}
}
Note : My tableview is embedded in a UIView (superview)
Update Swift 4.2:
1.call the activityIndicator function on viewDidLoad
eg:
var indicator = UIActivityIndicatorView()
override func viewDidLoad() {
//Initializing the Activity Indicator
activityIndicator()
//Starting the Activity Indicator
indicator.startAnimating()
//Call Your WebService or API
callAPI()
}
Here is the Code For Adding ActivityIndicator as Subview
func activityIndicator() {
indicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
indicator.style = UIActivityIndicatorView.Style.whiteLarge
indicator.color = .red
indicator.center = self.view.center
self.view.addSubview(indicator)
}
2. Do UI related Operations or API Call and stop activity indicator
func callAPI() {
YourModelClass.fetchResult(someParams,
completionHandler: { (response) in
//Do necessary UIUpdates
//And stop Activity Indicator
self.indicator.stopAnimating()
})
}
func setupSpinner(){
spinner = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 40, height:40))
spinner.color = UIColor(Colors.Accent)
self.spinner.center = CGPoint(x:UIScreen.main.bounds.size.width / 2, y:UIScreen.main.bounds.size.height / 2)
self.view.addSubview(spinner)
spinner.hidesWhenStopped = true
}
Using "lazy var". It's better than function
fileprivate lazy var activityIndicatorView: UIActivityIndicatorView = {
let activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
activityIndicatorView.hidesWhenStopped = true
// Set Center
var center = self.view.center
if let navigationBarFrame = self.navigationController?.navigationBar.frame {
center.y -= (navigationBarFrame.origin.y + navigationBarFrame.size.height)
}
activityIndicatorView.center = center
self.view.addSubview(activityIndicatorView)
return activityIndicatorView
}()
Just start the spinner anywhere
like this
func requestData() {
// Request something
activityIndicatorView.startAnimating()
}
#brocolli's answer for swift 4.0. You have to use objc_ before getting or setting associated objects. According to the documentation, The APIs of getting and setting the associated object in Swift are:
func objc_getAssociatedObject(object: AnyObject!,
key: UnsafePointer<Void>
) -> AnyObject!
func objc_setAssociatedObject(object: AnyObject!,
key: UnsafePointer<Void>,
value: AnyObject!,
policy: objc_AssociationPolicy)
Implementation:
import UIKit
fileprivate var ActivityIndicatorViewAssociativeKey = "ActivityIndicatorViewAssociativeKey"
extension UIView {
var activityIndicatorView: UIActivityIndicatorView {
get {
if let activityIndicatorView = objc_getAssociatedObject(self, &ActivityIndicatorViewAssociativeKey) as? UIActivityIndicatorView {
return activityIndicatorView
} else {
let activityIndicatorView = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
activityIndicatorView.activityIndicatorViewStyle = .gray
activityIndicatorView.color = .gray
activityIndicatorView.center = center
activityIndicatorView.hidesWhenStopped = true
addSubview(activityIndicatorView)
objc_setAssociatedObject(self, &ActivityIndicatorViewAssociativeKey, activityIndicatorView, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return activityIndicatorView
}
}
set {
addSubview(newValue)
objc_setAssociatedObject(self, &ActivityIndicatorViewAssociativeKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
In order to place the UIActivityIndicator in foreground, even over the eventual UITableViewController separators, I have adopted this solution.
I have add the UIActivityIndicator programmatically, and add it as a subview of my UINavigationController
var activityIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
// Code
// .... omissis
// Set activity indicator
activityIndicator = UIActivityIndicatorView(style: .whiteLarge)
activityIndicator.color = UIColor.darkGray
activityIndicator.center = tableView.center
activityIndicator.hidesWhenStopped = true
activityIndicator.stopAnimating()
self.navigationController?.view.addSubview(activityIndicator)
}
I have just start & stop it when needed (in my case):
func animateActivityIndicator(_ sender: Any ) {
guard let vc = sender as? UIViewController else { return }
if let v = vc as? MyTableViewController {
if v.activityIndicator.isAnimating {
v.activityIndicator.stopAnimating()
} else {
v.activityIndicator.startAnimating()
}
}
// Others UIViewController or UITableViewController follows...
// all of them exhibits an activityIndicator variable
// implemented programmatically or with the storyboard
}
PS. My environment is Xcode 10.0, iOS 12.0

Resources