2016-10-22 4 views
2

Я пытаюсь сохранить код и рефакторинг.Swift 3/Как повторно использовать расширения

В моем проекте я использую следующее расширение adMobBanner в нескольких UIViewController s.

Все расширение многоразовое, мне просто нужно изменить имя 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)") 
    } 
} 

ответ

1

удлиняет общий суперкласс всех пострадавших зрения контроллеров (возможно, сам UIViewController), то вы можете использовать код во всех подклассах.

+0

так 'extension UIViewController: GADInterstitialDelegate {'? –

+0

Да, именно :-) – vadian

+0

большое спасибо. я приму ваш ответ, так как это та же логика, что и во втором ответе, и ваша была первой –

2

Что до меня было до сих пор, так это создать собственный файл с именем "Name regarding to the content about-extension of class, а затем я поместил файл в папку группы с именем Extensions. Так что в вашем случае я бы назвал файл так:

GADInterstitialDelegate-UIViewControllerExtension.swift 

И код внутри так:

extension UIViewController: GADInterstitialDelegate { 
// your reusable code 
} 

Это просто мой подход, и я думаю, что есть и другие хорошие

+2

Большое спасибо за вашу помощь и вклад. но я соглашусь на другой ответ, потому что это та же логика и справедливость: он был первым (основанным на времени). но упрек для вашего времени и усилий –

+0

Добро пожаловать, конечно, это правда. Я просто хотел замедлить, как это описать наилучшим образом. В конце концов, это совершенно так же, за исключением подсказки к отдельному файлу – ronatory

Смежные вопросы