Reputation: 14030
I have multiple TableViewController
classes that inherit from a basic TableViewController
class like this:
class BasicTableViewController: UITableViewController {
}
class SpecificTableViewController: BasicTableViewController {
}
class AnotherSpecificTableViewController: BasicTableViewController {
}
then i created a very simple protocol to add refreshing capabilities to the specific viewcontroller classes like this:
@objc
protocol Refreshable {
func refresh()
}
my specific viewcontroller classes can implement the protocol like this:
class SpecificTableViewController: BasicTableViewController, Refreshable {
func refresh() {
getSomeDataFromServer()
}
}
the question now is: what is the correct way to call the refresh method from the BasicTableViewController
which itself does not conform to the Refreshable
protocol? right now i am doing something like this (without being sure if it's the way to go):
class BasicTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let _ = self as? Refreshable {
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(Refreshable.refresh), forControlEvents: .ValueChanged)
self.refreshControl = refreshControl
}
}
}
at the very beginning i did not mark the protocol with @objc
and tried to build the selector like this: #selector(refresh)
. that did not work though. hope to get some clarification. :)
thanks in advance!
Upvotes: 3
Views: 1389
Reputation: 4448
I would let the Superclass
implement the Refreshable
protocol
protocol Refreshable {
func refresh()
func shouldBeRefreshable() -> Bool
}
//Making the protocol methods optional
extension Refreshable {
func refresh() {}
func shouldBeRefreshable() -> Bool { return false}
}
class SuperView: Refreshable {
func addRefreshControl() {
if shouldBeRefreshable() {
//Add Refresh Control
}else {
// Do Nothing
}
}
func shouldBeRefreshable() -> Bool {
//default
return false
}
}
//Refreshable Class
class ChildA: SuperView {
func refresh() {
print("Refresh in Child A")
}
override func shouldBeRefreshable() -> Bool {
return true
}
}
//Not Refreshable Class
class ChildB: SuperView {
}
Upvotes: 1