728x90
반응형
▶️Segue prepare 메소드를 통해 전달하는 방식
▶️Property에 접근해서 전달하는 방식
▶️ Delegation을 통해 전달하는 방식
뷰를 전환하며 데이터를 전달하는 방식은 크게 2가지로 나뉩니다.
바로 직접 전달과 간접 전달이죠.
NotificationCenter를 통해 전달하는 방식은 직접 전달 방식에 해당합니다.
🔆 SecondVC의 textField의 text를 VC의 textLabel로 전달할 거에요!
VC : addObserver -> notification을 관찰한다. (전달받은 신호를 관찰해 함수를 실행)
SecondVC : post -> notification을 뿌린다. (원하는 데이터를 전달)
1️⃣ NotificationCenter post 해주기
NotificationCenter.default.post(name: NSNotification.Name("sample"), object: text)
sample이라는 notification에 textField의 text를 담아서 보낸다! 라는 뜻입니다.
object 에 text만 들어간 이유는 nil 값을 고려해서 옵셔널 바인딩을 해줬기 때문입니다.
2️⃣ NotificationCenter Observer 등록해주기
NotificationCenter.default.addObserver(self,
selector: #selector(dataReceived(_:)),
name: NSNotification.Name("sample"),
object: nil)
self!
여기 이! ViewController에서
"sample"이라는 notification이 생기면 dataReceived(_:) 함수를 실행할 것이다! 라는 뜻입니다.
3️⃣ 호출될 함수 작성해주기
@objc func dataReceived(_ notification: Notification) {
if let text = notification.object as? String {
dataLabel.text = text
}
}
그렇다면 이제 dataReceived 함수 안에 실행될 코드를 작성해줘야 합니다.
우리가 원하는 건 textField의 text가 label로 전달되는 것입니다.
object의 타입을 모르기 때문에
notification.object를 다운캐스팅을 통해서 String형으로 가져와서 text에 넣어줍니다.
결과화면
솝트 세미나 자료를 통해 예제를 진행해봤는데..
좀 더 다채로운 예제를 접해봐게써;;...
728x90
반응형
'⭐️ 개발 > iOS & Swift' 카테고리의 다른 글
[iOS] UIButton에 NSMutableAttributedString 적용해보기 (0) | 2021.08.04 |
---|---|
[iOS] TableView 최상단 cell, safeArea 무시하고 배치하는 법? (0) | 2021.08.02 |
[iOS] NotificationCenter? (0) | 2021.07.29 |
[iOS] Moya가 모야? - Moya로 Get 통신하기 (10) | 2021.07.25 |
[iOS] TextView - 플레이스홀더, 패딩, 글자 수 제한, 커서, 키보드 dismiss (0) | 2021.07.22 |