개발/아이오에스

ios] 코드로 UITabBarController의 탭에 UICollectionViewController를 선언하고 콜렉션뷰 설정하기(테이블뷰처럼)

dev.jake 2021. 3. 8. 19:59



class FeedController: UICollectionViewController-  UITabBarController에 선언되어있는 FeedController은 UICollectionViewController이다 이 상태로 런을 하면 'NSInvalidArgumentException', reason: 'UICollectionView must be initialized with a non-nil layout parameter'같은 에러가 나타난다  UICollectionView는 Nil이 아닌 레이아웃 매개 변수로 초기화해야 하기때문.

 

let layout = UICollectionViewFlowLayout()

let feed = templateNavigationController(unselectedImage:  imageLiteral(resourceName: "home_unselected"), selectedImage:  imageLiteral(resourceName: "home_selected"), rootViewController: FeedController(collectionViewLayout: layout))

 

이렇게 rootViewController을 선언하는 부분에 (collectionViewLayout: layout)으로 UICollectionViewFlowLayout으로 레이아웃 매개 변수 초기화를 해준다.

 

FeedController 에서

 func configureUI(){

        view.backgroundColor = .white

    }

whte로 백그라운드를 설정했었다.

 

하지만 실행을하면 배경이 검은색으로 보인다. 그 이유는 FeedController가 뷰컨트롤에서 UICollectionViewController으로 변했기 때문에

 func configureUI(){

        collectionView.backgroundColor = .white

    }

view가 아닌 collectionView의 백그라운드로 설정을 바꾸고 런을하면 

흰색으로 적용된 모습을 볼 수 있다.

 

이제 콜렉션뷰를 기본 설정하기위해 

extension FeedController: UICollectionViewDataSource{

    

}

UICollectionViewDataSource을 extension하여 설정을 하려했다 하지만 class FeedController: UICollectionViewController 

선언한 UICollectionViewController이 UICollectionViewDataSource이미 포함이 되어있어 extension 할 때UICollectionViewDataSource을 따로 적어 줄 필요가 없다

 

extension FeedController{

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return 5

    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuserIdentifier, for: indexPath)

        cell.backgroundColor = .red

        return cell

    }

}

 

func configureUI(){

        collectionView.backgroundColor = .white

        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuserIdentifier)

    }

register을 통해 콜렉션뷰를 선언해주고 cellForItemAt과 numberOfItemsInSection으로 섹션의 수와 셀을 설정해줬다.

 

 

이제 collectionView를 테이블뷰처럼 바꿔주는일을 해야한다.

 

extension FeedController: UICollectionViewDelegateFlowLayout{

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        return CGSize(width: view.frame.width, height: 250)

    }

}
UICollectionViewDelegateFlowLayout을 extension해서 가로의 길이를 view.frame.width 뷰의 width크기만큼으로 늘리고  세로를 250으로 설정해줬다.

 

 

코드를 통해 콜렉션뷰를 테이블뷰처럼 설정완료!