I'm trying to extract some of the code base for re use purpose. My approach is using Protocol and Protocol Extension instead of general BaseClass.
I have create the below a protocol and protocol extension
protocol MovieDisplay {
var collectionView: UICollectionView! { get set }
var refreshControl: UIRefreshControl! { get set }
}
extension MovieDisplay where Self: UIViewController {
var refreshControl: UIRefreshControl {
let rc = UIRefreshControl()
rc.backgroundColor = .clear
rc.tintColor = .lightGray
if #available(iOS 10.0, *) {
collectionView.refreshControl = rc
} else {
// Fallback on earlier versions
collectionView.addSubview(rc)
}
return rc
}
}
In my main class that adopt the protocol I declare like this (using default implementation of refreshcontrol)
class PopularMovieVC: UIViewController, MovieDisplay {
@IBOutlet weak var collectionView: UICollectionView!
}
The problem is function which involve refreshcontrol does not work. It works only when I explicitly declare refreshcontrol variable inside main class and convert extension into function and call it inside main class like below:
func setupRefreshControl() {
refreshControl.backgroundColor = .clear
refreshControl.tintColor = .lightGray
if #available(iOS 10.0, *) {
collectionView.refreshControl = refreshControl
} else {
// Fallback on earlier versions
collectionView.addSubview(refreshControl)
}
}
How to properly configure the protocol and protocol extension for default implementation?
It doesn't work because the computed property isn't called implicitly.
Adding this line in
viewDidLoadshould initialize the refresh controlIn this case I'd really prefer a base class