Project 18 - DataSource, Delegate

DaY·2021년 5월 12일
1

iOS

목록 보기
42/52
post-thumbnail

DataSource - 데이터를 받아 뷰를 그려주는 역할

Table View를 예시로, DataSource 메소드는 다음과 같다.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?

Delegate - 어떤 행동에 대한 "동작"을 제시

Table View를 예시로, Delegate 메소드는 다음과 같다.

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath)
func tableView(tableView: UITableView, willBeginEditingRowAtIndexPath indexPath: IndexPath) 
func tableView(tableView: UITableView, willBeginEditingRowAtIndexPath indexPath: IndexPath)

HorizontalScroller.swift

Horizontal Scroller라는 새로운 view를 만들어 사용할 예정이다.
먼저, 클래스 생성 후 DataSource와 Delegate 프로토콜을 커스텀해준다.

protocol HorizontalScrollerDataSource: class {
    func numberOfViews(in horizontalScrollerView: HorizontalScrollerView) -> Int
    
    func horizontalScrollerView(_ horizontalScrollerView: HorizontalScrollerView, viewAt index: Int) -> UIView
}

protocol HorizontalScrollerDelegate: class {
    func horizontalScrollerView(_ horizontalScrollerView: HorizontalScrollerView, didSelectViewAt index: Int)
}

extension HorizontalScrollerDataSource {
    func initialViewIndex(_ scroller: HorizontalScrollerView) -> Int {
        return 0
    }
}

이를 View Controller에서 사용한 모습

DataSource

extension ViewController: HorizontalScrollerDataSource {
    func numberOfViews(in horizontalScrollerView: HorizontalScrollerView) -> Int {
        return allAlbums.count
    }
    
    func horizontalScrollerView(_ horizontalScrollerView: HorizontalScrollerView, viewAt index: Int) -> UIView {
        let album = allAlbums[index]
        let albumView = AlbumView(frame: CGRect(x: 0, y: 0, width: 100, height: 100), coverUrl: album.coverUrl)
        
        if currentAlbumIndex == index {
            albumView.highlightAlbum(true)
        } else {
            albumView.highlightAlbum(false)
        }
        return albumView
    }
}

Delegate

extension ViewController: HorizontalScrollerDelegate {
    func horizontalScrollerView(_ horizontalScrollerView: HorizontalScrollerView, didSelectViewAt index: Int) {
        let previousAlbumView = scroller.viewAtIndex(currentAlbumIndex) as! AlbumView
        
        previousAlbumView.highlightAlbum(false)
        currentAlbumIndex = index
        
        let albumView = scroller.viewAtIndex(currentAlbumIndex) as! AlbumView
        
        albumView.highlightAlbum(true)
        showDataForAlbum(at: currentAlbumIndex)
    }
}

0개의 댓글