iOS/UIKit

[iOS / UIKit] Delegate을 활용하여 ViewController간 Data 전달하기

TDCIAN 2023. 4. 10. 12:05

안녕하세요~

오늘은 Delegate을 활용하여 두 ViewController 사이에 Data를 주고받는 방식을 한 번 알아봅시다!

모달 방식으로 보여지는 SendingViewController의 텍스트필드에 내용을 입력하고 'Send Data' 버튼을 클릭하면

해당 내용이 ReceivingViewController의 중앙에 있는 Label을 업데이트 시킵니다.

 

어떻게 만들었는지 바로 코드 보여드리겠습니다!

 

(1) 데이터를 받아 화면 중앙의 Label을 업데이트 시키는 ReceivingViewController입니다.

import UIKit
class ReceivingViewController: UIViewController {
private lazy var dataLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = .systemFont(ofSize: 16, weight: .medium)
label.textAlignment = .center
label.text = "NO DATA"
return label
}()
private lazy var popupButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("Popup SendingVC", for: .normal)
button.setTitleColor(.white, for: .normal)
button.backgroundColor = .systemBlue
button.layer.cornerRadius = 16
button.addTarget(self, action: #selector(didTapPopupButton), for: .touchUpInside)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
title = "ReceivingViewController"
view.backgroundColor = .green
setLayout()
}
private func setLayout() {
view.addSubview(dataLabel)
view.addSubview(popupButton)
NSLayoutConstraint.activate([
dataLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
dataLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor)
])
NSLayoutConstraint.activate([
popupButton.topAnchor.constraint(equalTo: dataLabel.bottomAnchor, constant: 25),
popupButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
popupButton.widthAnchor.constraint(equalToConstant: 200),
popupButton.heightAnchor.constraint(equalToConstant: 50),
])
}
@objc private func didTapPopupButton() {
let sendingVC = SendingViewController()
// MARK: !! SendingViewController에 선언된 delegate를 self(ReceivingViewController)로 설정합니다. !!
sendingVC.delegate = self
sendingVC.modalPresentationStyle = .pageSheet
sendingVC.sheetPresentationController?.detents = [.medium()]
sendingVC.sheetPresentationController?.prefersGrabberVisible = true
present(sendingVC, animated: true)
}
}
extension ReceivingViewController: DataDelegate { // DataDelegate를 implementation 해줍니다.
/*
- SendingViewController에서 delegate가 위임을 하면 해당 내용을 ReceivingViewController가 구현합니다.
- 이 프로젝트에서는 SendingViewController.swift의
delegate?.sendData(data: dataTextField.text ?? "Nothing left to say")
함수가 호출되었을 때 입니다.
*/
func sendData(data: String) {
dataLabel.text = "Received data: \(data)"
}
}

(2) TextField에 입력된 내용을 Notification을 통해 ReceivingViewController로 전달하는 SendingViewController입니다.

import UIKit
// 데이터를 전달할 Delegate 프로토콜을 정의합니다.
protocol DataDelegate: AnyObject {
func sendData(data: String)
}
class SendingViewController: UIViewController {
// Delegate를 선언해줍니다.
weak var delegate: DataDelegate?
private lazy var dataTextField: UITextField = {
let textField = UITextField()
textField.translatesAutoresizingMaskIntoConstraints = false
textField.borderStyle = .roundedRect
textField.placeholder = "Input some data"
return textField
}()
private lazy var sendButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("Send Data", for: .normal)
button.setTitleColor(.white, for: .normal)
button.backgroundColor = .systemBlue
button.layer.cornerRadius = 16
button.addTarget(self, action: #selector(didTapSendButton), for: .touchUpInside)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
title = "SendingViewController"
view.backgroundColor = .systemYellow
setLayout()
}
private func setLayout() {
view.addSubview(dataTextField)
view.addSubview(sendButton)
NSLayoutConstraint.activate([
dataTextField.centerXAnchor.constraint(equalTo: view.centerXAnchor),
dataTextField.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 150),
dataTextField.widthAnchor.constraint(equalToConstant: 200),
dataTextField.heightAnchor.constraint(equalToConstant: 45),
])
NSLayoutConstraint.activate([
sendButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
sendButton.topAnchor.constraint(equalTo: dataTextField.bottomAnchor, constant: 50),
sendButton.widthAnchor.constraint(equalToConstant: 120),
sendButton.heightAnchor.constraint(equalToConstant: 50),
])
}
@objc private func didTapSendButton() {
// 텍스트필드에 입력된 내용이 delegate를 통해 ReceivingViewController로 전달되게 합니다.
delegate?.sendData(data: dataTextField.text ?? "Nothing left to say")
dismiss(animated: true)
}
}

 

전체 소스코드가 들어 있는 깃허브 주소입니다!

https://github.com/TDCIAN/PassDataUsingDelegate

 

GitHub - TDCIAN/PassDataUsingDelegate

Contribute to TDCIAN/PassDataUsingDelegate development by creating an account on GitHub.

github.com

 

 

Delegate이 아니라 Notification으로 Data를 전달하는 아래 내용은 어떠세요?

 

https://tdcian.tistory.com/355

 

[iOS / UIKit] Notification을 활용하여 ViewController간 Data 전달하기

안녕하세요~ 오늘은 Notification을 활용하여 두 ViewController 사이에 Data를 주고받는 방식을 한 번 알아봅시다! 모달 방식으로 보여지는 SendingViewController의 텍스트필드에 내용을 입력하고 'Send Data'

tdcian.tistory.com

 

 

 

Delegate과 Notification을 비교한 아래 내용은 어떠세요?

https://tdcian.tistory.com/357

 

[iOS / UIKit] Notification과 Delegate으로 Data를 주고받는 것에 관하여

안녕하세요! 앞서 두 글을 소개한 바 있습니다! (1) Notification을 활용하여 ViewController 간 Data 전달하기 https://tdcian.tistory.com/355 [iOS / UIKit] Notification을 활용하여 ViewController간 Data 전달하기 안녕하세

tdcian.tistory.com