반응형
LinkedIn 개발자로 성장하면서 남긴 발자취들을 확인하실 수 있습니다.
Github WWDC Student Challenge 및 Cherish, Tiramisul 등 개발한 앱들의 코드를 확인하실 수 있습니다.
개인 앱 : Cherish 내 마음을 들여다보는 시간, 체리시는 디자이너와 PM과 함께 진행 중인 1인 개발 프로젝트입니다.
10년 후, 20년 후 나는 어떤 스토리 텔러가 되어 있을지 궁금하다. 내가 만약에 아직 조금 더 탐구하고 싶은 게 있고, 궁금한 게 있다면, 그게 설사 지금 당장의 내 인생에 도움이 안 되는 것 같더라도 경험해보자. 그 경험들을 온전히 즐기며 내 것으로 만들고, 내 일에 녹여내고... 그러다보면 그 점들이 모여 나란 사람을 그려내는 선이 될 테니까.

Recent Posts
Recent Comments
Total
관리 메뉴

꿈꾸는리버리

delegate란? (예제) (2/2) 본문

오뚝이 개발자/UIKit

delegate란? (예제) (2/2)

rriver2 2022. 7. 24. 21:14
반응형

이전 포스팅에서는 아주 간단한 예제를 통해서 delegate가 뭔지에 대해 알아봤다

이번 포스팅에서는 실제 UIKit 에서 어떻게 쓰이는 지 예시를 통해 알아보도록 하겠다 !

 

🌷 하고자 하는 것

FirstViewController 에서 SecondViewController로 이동을 하고, 

SecondViewController의 textField에서 입력한 값을 FirstViewController에 보여주는 것 !

 

 

SecondViewController에서 FirstViewController로 값을 보낼 때 delegate를 이용해서 보내줄 거다.

-> SecondViewController에서 FirstViewController로 text 값을 넘겨주면 FirstViewController에서 하늘색 뷰의 label text를 바꿔준다.

즉 , SecondViewController가 하늘색 뷰의 label text를 변경하는 대신, FirstViewController가 하늘색 뷰의 label text를 변경해준다.

 

 

지난 포스팅에 따르면 delegate를 구현하는 순서가 다음과 같았다.

1️⃣ protocol 선언

2️⃣ 대신 일을 하는 FirstViewController에서 protocol 채택

3️⃣ 대신 일을 하는 FirstViewController에서 protocol 요구사항 구현

4️⃣ 대신 일을 하는 FirstViewController와 일을 시키는 SecondViewController 연결

 


  🌷 자 이제 코드로 구현해보자  

1️⃣ protocol 선언

이렇게 label에 값을 넣는 기능을 하는 writeLabel 함수를 요구하는 Writable 프로토콜을 선언한다.

protocol Writable: AnyObject {
    func writeLabel(text: String)
}

 

2️⃣ 대신 일을 하는 FirstViewController에서 protocol 채택

Writable 프로토콜을 대신 일을 할 FirstViewController에서 채택한다.

-> 즉, FirstViewController에서 writeLabel 함수의 일을 수행하겠다는 말이다.

class FirstViewController: UIViewController, Writable {
	// code
}

 

3️⃣ 대신 일을 하는 FirstViewController에서 protocol 요구사항 구현

class FirstViewController: UIViewController, Writable {

    @IBOutlet var label: UILabel!

    func writeLabel(text: String) {
        label.text = text
    }
    
      // code들
    
}

 

4️⃣ 대신 일을 하는 FirstViewController와 일을 시키는 SecondViewController 연결

// FirstViewController
class FirstViewController: UIViewController, Writable {

   // code 들
    
    @IBAction func clickedNextButton(_ sender: UIButton) {
        guard let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as? SecondViewController else { return }
        self.present(nextViewController, animated: true)  // 해당 코드가 이해가 안된다면 하단의 링크 참고
        
        // 다음 nextViewController(SecondViewController)의 delegate 프로퍼티들 
        // self 즉, FirstViewController라고 명시
        nextViewController.delegate = self
    }
    
}
// SecondViewController
class SecondViewController: UIViewController {
    
    // delegate로 Writable을 명시
    weak var delegate: Writable?

    @IBOutlet weak var textField: UITextField!
    
    @IBAction func clickedPreView(_ sender: UIButton) {
        guard let text = textField.text else { return }
        
        // delegate의 writeLabel 함수를 실행
        delegate?.writeLabel(text: text)
        
        self.dismiss(animated: true)
    }
    
}

 


 

이번에는 짧은 예제를 통해 delegate를 UIKit에 적용해보았다 !

다음에는 CollectionView 예제를 통해서 좀 더 깊이있는 내용을 다뤄보려 한다 :)

누군가에게는 .. 도움이 되었길 바라보면서, 언제나 질문과 틀린 사항은 댓글로 알려주길 바라요 !!!

 


 

  전체코드  

1) FirstViewController

import UIKit

protocol Writable: AnyObject {
    func writeLabel(text: String)
}

class FirstViewController: UIViewController, Writable {

    @IBOutlet var label: UILabel!
    @IBOutlet weak var nextButton: UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    
    func writeLabel(text: String) {
        label.text = text
    }
    
    @IBAction func clickedNextButton(_ sender: UIButton) {
        guard let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as? SecondViewController else { return }
        self.present(nextViewController, animated: true)
        nextViewController.delegate = self
    }
    
}

 

2) SecondViewController

import UIKit

class SecondViewController: UIViewController {
    
    weak var delegate: Writable?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    @IBOutlet weak var textField: UITextField!
    @IBAction func clickedPreView(_ sender: UIButton) {
        guard let text = textField.text else { return }
        delegate?.writeLabel(text: text)
        self.dismiss(animated: true)
    }
    
}

 

해당 프로젝트 zip이다 ! 혹시 code로 보고 싶은 사람은 참고하길..!

practice.zip
0.04MB

 

 

 

+) 해당 코드가 이해가 안되는 사람은 이 블로그를 참고해보길 !

  guard let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as? SecondViewController else { return }
        self.present(nextViewController, animated: true)

 

 

반응형
Comments