Reputation: 4632
I have two view controllers SymbolsVC
and ItemsVC
. Both have a UIActivityIndicatorView which has been outlet by the name of spinner
in each view controller like this:
class SymbolsVC: UIViewController {
@IBOutlet weak var spinner: UIActivityIndicatorView!
}
class ItemsVC: UIViewController {
@IBOutlet weak var spinner: UIActivityIndicatorView!
}
Now I need to write a lot of shared code between these view controllers, for example, a function which would start the spinner in its respective viewcontroller. So I have created an extension for UIViewController like this:
extension UIViewController {
func startSpinner() {
spinner.startAnimating()
}
}
However, this gives Use of unresolved identifier 'spinner' error.
What am I missing?
EDIT FOR FURTHER CLARIFICATION: My extension is actually an IAP. This IAP can be called from any number of ViewControllers. When one of the ViewControllers, call the IAP function which is in the extension, it is the flow of the program in that IAP function which determines when to start/stop the spinner. Hence it needs to be done within the extension.
Upvotes: 1
Views: 859
Reputation: 685
When the compiler sees this:
extension UIViewController {
func startSpinner() {
spinner.startAnimating()
}
}
it thinks every instance of UIViewController in your module contains this spinner property, which of coarse is wrong.
Since as a rule, you can't place regular {set get} properties inside extension, my solution would be placing the spinner inside a base view controller SpinnerBaseVC
, which inherits UIViewController.
Then, inherit SpinnerBaseVC
with whatever class you want to utilize the spinner property.
class SpinnerBaseVC: UIViewController {
@IBOutlet weak var spinner: UIActivityIndicatorView!
func startSpinner() {
spinner.startAnimating()
}
}
// MARK: Classes which can naturally access `spinner` and `startSpinner`
class SymbolsVC: SpinnerBaseVC {
// Here you can access spinner
}
class ItemsVC: SpinnerBaseVC {
// Here you can access spinner
}
Upvotes: 2