我试图保存代码和重构。
在我的项目中,我在多个adMobBanner
中使用了以下UIViewController
扩展名。
整个扩展是可重用的,我只需要更改ViewController的名称:
extension MyVC: GADInterstitialDelegate {
但由于我在几个班级中使用它,这些班级的长度会不必要地超过。
是否有某种方法可以重复使用扩展程序?类似的东西:
func myExtension(vc: UIViewController) {
extension vc: GADInterstitialDelegate {
....
}
}
由myExtension(MyViewController)
我知道这段代码是无稽之谈,但它提供了我想要转置的想法。有什么相似的吗?或者用重复代码保存扩展代码行的另一种选择是什么?非常感谢帮助。
我的推广:
extension MyViewController: GADInterstitialDelegate {
// MARK: - Setup Ads
func setupAds() {
// Setup our interstitial ad initially
interstitial.delegate = self
interstitial.load(GADRequest())
}
// MARK: - Load Interstitial Ad
func loadFullScreenAd() {
// GADInterstitial's are single use. You have to create a new GADInterstitial for each presentation
// So, if you'd like to show more than one GADInterstitial in your apps session we need this
// This func will be used to create a new GADInterstitial after one has been displayed and dismissed
interstitial = GADInterstitial(adUnitID: getAdmobInterstitial())
interstitial.delegate = self
interstitial.load(GADRequest())
}
// MARK: - Show Interstitial Ad
func showFullScreenAd() {
// Call this function when you want to present the interstitial ad
// ie. game over, transition to another vc, etc...
// Make sure you give atleast a few seconds for this ad to load before atempting to present it
// For example, don't try to present this ad in viewDidAppear
// Check if the interstitial ad is loaded before trying to present it
if self.interstitial.isReady {
self.interstitial.present(fromRootViewController: self)
}
}
// MARK: - GADInterstitial Delegate Methods
func interstitialDidReceiveAd(_ ad: GADInterstitial!) {
print("interstitialDidReceiveAd")
showFullScreenAd()
}
func interstitialWillPresentScreen(_ ad: GADInterstitial!) {
print("interstitialWillPresentScreen")
// If you needed to pause anything in your app this would be the place to do it
// ie. sounds, game state, etc...
}
func interstitialDidDismissScreen(_ ad: GADInterstitial!) {
print("interstitialDidDismissScreen")
// The GADInterstitial has been shown and dismissed by the user
// Lets load another one for the next time we want to show a GADInterstitial
//loadFullScreenAd()
// If you paused anything in the interstitialWillPresentScreen delegate method this is where you would resume it
}
func interstitial(_ ad: GADInterstitial!, didFailToReceiveAdWithError error: GADRequestError!) {
print("interstitial didFailToReceiveAdWithError: \(error)")
}
}
答案 0 :(得分:2)
到目前为止对我有用的是创建一个名为"Name regarding to the content about-extension of class
的自己的文件,然后将该文件放在名为Extensions
的组文件夹中。所以在你的情况下,我会像这样调用文件:
GADInterstitialDelegate-UIViewControllerExtension.swift
里面的代码是这样的:
extension UIViewController: GADInterstitialDelegate {
// your reusable code
}
这只是我的方法,我认为还有其他好的方法
答案 1 :(得分:1)
扩展所有受影响的视图控制器的公共超类(可能是UIViewController
本身),然后您可以在所有子类中使用该代码。