[ios] 이전 화면으로 데이터 전달 - 클로저 사용하기

Cobugi·2021년 9월 19일
1

ios

목록 보기
5/8

이전 화면으로 데이터 전달(클로저 사용)

  • 데이터를 전달 받을 ViewController
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var dataLabel: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func tapNextBarButton(_ sender: UIBarButtonItem) {
        
        // 다음 화면으로 가기(identifier: StoryboardID)
        guard let nextViewController = self.storyboard?.instantiateViewController(identifier: "NextViewController") as? NextViewController else { return }
        
        nextViewController.modalPresentationStyle = .fullScreen
        
        // 다음 화면으로 가면서 클로져를 정의해준다
        nextViewController.dataSendClosure = { data in
            self.dataLabel.text = data
        }
        
        self.present(nextViewController, animated: true, completion: nil)
    }
}
  • 데이터를 전달 할 ViewController
import UIKit

class NextViewController: UIViewController {

    // 데이터 전달 클로저
    var dataSendClosure: ((_ data: String) -> Void)?
    
    override func viewDidLoad() {
        super.viewDidLoad()

    }
    
    @IBAction func tapNoDataButton(_ sender: UIButton) {
        self.dismiss(animated: true, completion: nil)
    }
    
    @IBAction func tapYesDataButton(_ sender: UIButton) {

        // 버튼을 누르면 클로져를 실행해라
        // 클로져의 정의는 전달 받는 뷰컨에서 한다(다음 화면으로 갈 때 정의한다)
        self.dataSendClosure?("이전 화면에서 전달 받음")
        
        self.dismiss(animated: true, completion: nil)
    }
}

더 많은 전달 보러가기

profile
iOS Developer 🐢

0개의 댓글