[Swift] 스위프트 - swift protocol delegate beetween two view controller without segue

두개의 뷰를 준비한다.

ViewController

SecondViewController


SecondViewController 에서 protocol 을 생성한다.

protocol SendImageData {
    func sendImg(img : UIImage)  // 나는 이미지를 넘겨야 해서 이런식으로 코딩함.

}

그리고 나서 
class SecondViewController : UIViewController{
   var delegate: SendImageData? = nil  // 초기화 및 선언을 해준다.

   //...
}

데이터를 넘겨받을 ViewController 에서는

class ViewController : UIViewController, SendImageData {  //delegate pattern 을 이용해준다.

  //그리고 세컨드뷰로 이동하는 소스안에다가 
  @IBAction func nextBtn(sender: UIButton) {
        let uvc = self.storyboard!.instantiateViewControllerWithIdentifier("secondPage")  as! SecondViewController

        uvc.delegate = self   //이부분이 핵심!!
        
        uvc.modalTransitionStyle = UIModalTransitionStyle.CrossDissolve
        
        self.presentViewController(uvc, animated: true, completion: nil)
    }

  func sendImg(img : UIImage){   //SecondViewController 에서 프로토콜안에 정의한 함수를 구현해준다. 주의할 점은 이 함수는 ViewController 안이라는 것이다.
       // 원하는 소스
  }


}

댓글