2017-07-06 22 views
1

我有一個子視圖,它接管整個父視圖。我希望通過使用協議從父級調用方法將子級從父級中移除,但我的代表每次都是零。我下面添加我的樣本工作,如果你需要更多的信息,只是讓我知道我試圖從父母刪除孩子時,我們的代表爲零swift 3

protocol childDelegate: class { 
      func removeFromParent() 
     } 
     class ChildAction: UITableViewController { 
      @IBAction func btnRemove(_sender: Any){ 
       if(delegate != nil){ 
       self.delegate?.removeFromParent() 
      } 
      } 
     } 
     class ParentClass: UIViewController:childDelegate { 

     var delegate:childDelegate? 
     private ChildActionView:ChildAction{ 
      let storyboard = UIStoryBoard(name: "Main", bundle: Bundle.main) 
      let viewC = storyboard.instantiateViewController(withIdentifier: "ChildAction") as! ChildAction 
       self.delegate = viewC as? childDelegate 
       self.addChildViewController(viewC) 
       return viewC 

     } 
     @IBAction func btnAddChild(_sender: Any){ 
       addChild(child:ChildActionView) 
      } 

     func addChild(child: UIViewController){ 
      self.addChildViewController(child) 
      view.addSubview(child.view) 
      child.didMove(toParentViewController: self) 
     } 

      func removeFromParent(){ 
       //remove from parent 

      } 
     } 

Child view controller parent view controller image

+0

@DharmeshKheni我的代碼片段 –

+0

下增加了兩個圖像刪除所有代碼的圖像。複製全部代碼 – Honey

+0

@Honey你釘了它 –

回答

1

無論在哪裏在你的代碼你設置你的ChildAction實例(您childVC)的delegate變量。您爲孩子設置了parent's delegate,但這在代碼中沒有意義。您需要將child's delegate設置爲父級。目前,孩子沒有任何父母的參考,所以其代表自然是nil。讓我知道,如果有什麼不清楚。

1

我強烈建議您閱讀關於委託模式的文章或教程。如果你基本瞭解假設的工作原理,事情會變得更容易。

將此代碼與您發佈的內容進行比較。看看它是否有道理。

protocol childDelegate: class { 
    func removeFromParent() 
} 

class ChildAction: UIViewController { 

    // this class gets the delegate, because it wants to "call back" to a delegated function 
    var delegate:childDelegate? 

    @IBAction func btnRemove(_sender: Any){ 
     // IF delegate has been assigned, call its function 
     delegate?.removeFromParent() 
    } 
} 

class ParentClass: UIViewController, childDelegate { 

    // bad naming... would be much clearer if it was "childActionViewController" or "childActionVC" 
    private let ChildActionView: ChildAction = { 
     let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main) 
     let viewC = storyboard.instantiateViewController(withIdentifier: "ChildAction") as! ChildAction 
     return viewC 

    }() 

    @IBAction func btnAddChild(_sender: Any){ 
     // add the child view controller 
     self.addChildViewController(ChildActionView) 
     // set its delegate to self 
     ChildActionView.delegate = self 
     // add its view to the hierarchy 
     view.addSubview(ChildActionView.view) 
     // finish the process 
     ChildActionView.didMove(toParentViewController: self) 
    } 

    func removeFromParent() { 
     //remove from parent 
     print("removeFromParent() called...") 
    } 

} 
+0

你是對的我看到我的錯誤我會檢查一些教程,以更好地瞭解委託模式 –

相關問題