简体   繁体   中英

Passthrough clicks, events from Child View Controller to Parent View Controller

I have some buttons in Child View Controller. I'd like a user to be able to click on these buttons, and, in case he clicks in other area, Parent View Controller to be able to process those clicks that Child View Controller doesn't work with.

You need to create protocols and delegates.

protocol Vc2Delegate : AnyObject {
  func buttonPressed()
}

class Vc1 : UIViewController, Vc2Delegate {
  func presentVC2() {
     let vc2 = Vc2()
     vc2.delegate = self
     present(vc2)
 }

 func buttonPressed() {
      // process vc2 button press in vc1
 }

}

class Vc2 : UIViewConttoller {

  // weak !!!!
  weak var delegate : Vc2Delegate? = nil

  func buttonInVc2Pressed() {
      // call func in vc1 from vc2
     delegate?.buttonPressed()
  }

}

PS Sorry for formatting, was wrote from iPhone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM