Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- Value Type Reference Type
- Input Output
- 면접을 위한 CS 전공 지식 노트 Tree
- 면접을 위한 CS전공 지식 노트
- coremotion
- SWIFT
- Array vs Linked List
- til
- 테이블뷰 나누기
- TableView
- wil
- 강한 참조 순환
- NavigationSearchBar
- CarouselCollectionview
- retain cycle
- class struct
- UserDefaults
- tableview section별 다른 cell적용
- UIKit
- CoreData
- 프로그래머스
- @escaping
- firebase
- Carousel CollectionView
- 자료구조
- TableView Section
- 롤케이크 자르기
- ReferceCycle
- Reference Cycle
- 양궁대회
Archives
- Today
- Total
개발하는 동글 :]
[TIL],[TRY],[Delegate 패턴적용하기] 본문
1. Custom Delegate 구현하기
memoView.contentTextView.delegate = self
memoView.optionCollectionView.delegate = self
memoView.optionCollectionView.dataSource = self
평소 커스텀 뷰를 사용하며 커스텀 뷰에 포함된 collectionView 및 textView 등 다양한 컴포넌트의 delegate들을 이런 식으로 사용해 왔다. 그러다 문득 이러한 델리게이트를 통합하면 어떨까?라는 생각을 하여 구현을 시도해 보았다. 먼저 memoview에서 사용 될 collectionview만 하나로 만드는 작업으로 실험을 해 보았다. collection의 delegate와 datasoure에서 사용하는 메서드들 중 필요한 메서드를 프로토콜에 정의하였다.
protocol MemoViewDelegate: UIViewController {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
}
view에 delegate 를 만들고 delegate와 datasoure를 뷰에 할당해 준 뒤 각 메서드에 아래의 코드와 같이 작성하였다.
weak var delegate: MemoViewDelegate?
extension MemoView: UICollectionViewDelegate, UICollectionViewDataSource, UITextViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let delegate = delegate else { return 0}
return delegate.collectionView(collectionView, numberOfItemsInSection: section)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let delegate = delegate else { return UICollectionViewCell()}
return delegate.collectionView(collectionView, cellForItemAt: indexPath)
}
}
controller로 돌아와 커스텀 뷰의 델리게이트를 controller로 할당해 주고 기존처럼 사용해 주면 끝이다.
extension MemoViewController: MemoViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
<#code#>
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
<#code#>
}
}
2. 이유가 없는 코드
이러한 작업을 하고 느낀점은 왜 이렇게 코드를 작성하였는가 인데 delegate 및 datasoure를 하나로 묶고 싶었다는 이유는 한 작업 대비 이유가 되지 않는다고 생각한다. 또 한 기능적으로 무언가 잘못된 부분이 있음에도 인지하지 못하고 있을 가능성도 있다고 생각한다. 그렇기에 나는 이 코드를 팀프로젝트에 적용하지 않았고 앞으로 코드를 짤 때에도 이유가 있는 코드를 짜기 위한 노력을 해야겠다.