2017-08-15 112 views
0

我有一個覆蓋視圖來隔離內容,我在viewWillAppear()中檢查身份驗證,並且我有一個通知訂閱了我的Auth方法。如果在我的任何其他視圖出現之前進行身份驗證,疊加層不會顯示出來,但它在第一個視圖上執行並且即使在調用removeFromSuperView()後也不會消失。SubView(nib)在調用remove後不會刪除removeFromSuperView()

import UIKit 
import FirebaseAuth 

class ProtectedViewController: UIViewController, ForceSignInBannerDelegate, 
SignUpViewControllerDelegate, LoginViewControllerDelegate{ 


override func viewDidLoad() { 
    super.viewDidLoad() 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 

override func viewDidAppear(_ animated: Bool) { 
    super.viewDidAppear(true) 
    NotificationCenter.default.addObserver(self, selector: #selector(checkAuthentication), name: .myNotification, object: nil) 
} 

override func viewWillAppear(_ animated: Bool) { 
    super.viewWillAppear(true) 
    self.checkAuthentication() 

} 

func checkAuthentication() { 
    let bannerViewController = ForceSignInBanner.instanceFromNib() as! ForceSignInBanner 
    bannerViewController.delegate = self 

     if (!AuthenticationService.sharedInstance.isAuthenticated()) { 
      self.setView(view: bannerViewController, hidden: false) 
      print("Need to login") 
     } else if(AuthenticationService.sharedInstance.isAuthenticated()) { 
      self.setView(view: bannerViewController, hidden: true) 
     } 
    } 

func setView(view: UIView, hidden: Bool) { 
    UIView.transition(with: view, duration: 0.5, options: .transitionCrossDissolve, animations: { _ in 

     view.isHidden = hidden 
     if hidden { 
      view.removeFromSuperview() 
     } else { 
      self.view.addSubview(view) 
     } 

    }, completion: nil) 
} 

回答

1

這是因爲您試圖每次刪除新的ForceSignInBanner。理想情況下,您應該創建一次並保留對創建的ForceSignInBanner的引用(作爲ProtectedViewController的可選屬性)。

然後刪除您存儲在屬性中的ForceSignInBanner

class ProtectedViewController: UIViewController, ForceSignInBannerDelegate { 

     // This lazily loads the view when the property is first used and sets the delegate. 
     // Ideally you wouldn't force-case the `as` but I've left it for simplicity here. 

     private lazy var forceSignInBannerView: ForceSignInBanner = { 
      let forceSignInBannerView = ForceSignInBanner.instanceFromNib() as! ForceSignInBanner 
      forceSignInBannerView.delegate = self 
      return forceSignInBannerView 
     }() 

     // ... your other code ... // 

     fun toggleForceSignInBannerViewVisibility(isVisible: Bool) { 
      if isVisible { 
       view.addSubview(forceSignInBannerView) 
      } else { 
       forceSignInBannerView.removeFromSuperview() 
      } 
     } 

    } 
+0

你有這樣的代碼示例嗎? –

+0

我已經添加了一些代碼。 –

+0

謝謝,我以某種方式想通了,我也會嘗試你的實現。 –

相關問題