본문 바로가기
Swift 개발 이야기

RxSwift로 여러가지 Custom TableView Cell 을 설정하기

by 방화동한량 2019. 5. 28.
728x90

RxSwift 는 TableView 를 쓰기 편하게 만들어두긴 했는데

 

하나의 테이블뷰에 하나의 셀만 설정하는 것에 약간 특화가 되어 있습니다.

 

    
        ListViewModel.data.bind(to: tableView.rx.items(cellIdentifier: "Cell")) {
            
            row, item, cell in
            
            //여기서 cell 의 값을 주는 방법으로 자주 씁니다
            
        }

 

하지만 실무에서는 하나의 테이블뷰에 여러가지 커스텀뷰를 넣어야 하는 경우가 있는데요.

 

이때는 아래와 같이 쓰시면 됩니다.

 		tableView.register(CustomRxTableViewCell.self, forCellReuseIdentifier: "Cell")
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "BasicCell")
       //테이블뷰에 언제나처럼 커스텀 클래스를 등록해줍니다.
       
      ListViewModel.data.bind(to: tableView.rx.items){(tv, row, item) -> UITableViewCell in

            if row == 0 {
                let cell = tv.dequeueReusableCell(withIdentifier: "BasicCell", for: IndexPath.init(row: row, section: 0))
                
                cell.textLabel?.text = item.name
                return cell
            }else{
                let cell = tv.dequeueReusableCell(withIdentifier: "Cell", for: IndexPath.init(row: row, section: 0)) as! CustomRxTableViewCell
                cell.titleLb.text = item.name
                return cell
            }

        }.disposed(by: disposeBag)

 

이런 식으로 하게 되면 기존의 cellForRowAt 을 사용하는 것처럼 custom Cell 을 사용할 수가 있게 됩니다.