iOS

[iOS] UICollectionViewDelegate

yevdev 2022. 9. 15. 10:24

🌱 UICollectionViewDelegate

- 사용자와 CollectionView의 아이템 사이의 상호작용을 관리해주기 위한 객체들에 의해 채택된 방식

- 이 프로토콜의 메소드들은 모두 Optional!

 

이 프로토콜을 통해 CollectionView의 Cell 클릭시 일어날 이벤트를 설정할 수 있다.

 

 

 

 


 

 

실습 해볼 내용

- HomeViewController의 CollectionViewCell 클릭 시, PlayerViewController를 가져와서 HomeView 에서 PlayerView로 전환시켜보겠다

extension HomeViewController: UICollectionViewDelegate {
    // 클릭했을때 어떻게 할까?
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        // TODO: 곡 클릭시, 플레이어 뷰 띄우기
        
    }
}

↑ 일단 이렇게 CollectionView 아이템 사이의 상호작용을 관리해주기 위해 UICollectionViewDeleagate 프로토콜을 extension

 

 

불러올 PlayerViewController의 Storyboard ID 설정

이 Storyboard ID를 통해 스토리보드를 가져오고 해당 ViewController을 가져올 것이다!

 

 

구현코드

extension HomeViewController: UICollectionViewDelegate {

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    
    	let playerStoryboard = UIStoryboard.init(name: "Player", bundle: nil)
        
        guard let playerVC = playerStoryboard.instantiateViewController(withIdentifier: "PlayerViewController") as? PlayerViewController else { return }

        present(playerVC, animated: true, completion: nil)
    }
}

 

instantiateViewController(withIdentifier:) : 지정된 식별자(:withIdentifier)을 가지고 스토리보드의 데이터를 초기화해 뷰 컨트롤러(=새로운 instance)를 만든다.

present() : 뷰 위에 새로운 뷰가 얹어지는 형태 (세로 방향 전개)

- completion : 뷰 이동 후, 실행될 블록

 

 

🚀 구현 화면

보다시피 아직 데이터는 연동 X (storyboard에 지정된 데이터만 보여짐)

그냥 뷰만 연결되어진 상태

 

 

데이터 연결에 대한 자세한 내용은 아래 포스팅으로!

..updating

 

 

 


Reference

- Apple Developer Document