2017-05-17 1 views
1

내비게이션 컨트롤러 내부에서 UICollectionViewCells를 사용하여 ViewController를 설정했습니다. 셀을 클릭 한 다음 선택한 셀 (각 셀에 대해 다른 컨트롤러)에 따라 사용자를 새 컨트롤러로 가져 오게 할 수 있습니다. 탐색 막대를 새 컨트롤러에 계속 나타나게하고 원래의 ViewController로 되돌아 갈 수있는 뒤로 단추가 있어야합니다. 컬렉션 뷰 셀을 설정하기 위해 초기 뷰 컨트롤러 내에 다음 코드가 있습니다.UICollectionViewCell을 클릭하면 새 컨트롤러로 전환하는 방법 (프로그래밍 방식으로)

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
    return 2 
} 

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: playlistCellId, for: indexPath) as! playlistCoverCell 

    return cell 
} 

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 
    return CGSize(width: 100, height: 100) 
} 

또한 viewDidLoad에 셀을 올바르게 등록합니다. 셀을 선택할 때 어떤 기능을 수행하기 위해 어떤 기능을 사용합니까?

답변

1

당신은 사용해야합니다 :

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 

     if indexPath.row == 0 { 
      let viewController = UIViewController() // or your custom view controller 
      self.navigationController?.pushViewController(viewController, animated: true) 
     } 
     else if indexPath.row == 1 { 
     // and so on.... 
     } 
} 

지정된 인덱스 경로에있는 항목이 선택 했다 대리자를 알려줍니다. 콜렉션 뷰는 사용자 이 콜렉션 뷰에서 항목을 성공적으로 선택할 때이 메소드를 호출합니다. 프로그래밍 방식으로 선택 영역을 설정할 때 메서드를 호출하지 않습니다.

+0

indexPath.row는 무엇을 나타 냅니까? 예를 들어 두 개의 셀이 있는데이 함수를 호출하고이 코드를 작성하면 : if indexPath.row == 0' - 첫 번째 셀이 선택되었음을 의미합니까? –

+1

첫 번째 셀의 인덱스는 0입니다. 셀이 3 개인 경우 인덱스가 0,1,2가됩니다. indexPath.section은 섹션을 나타냅니다 (하나만있는 경우 0). – mat

+0

저에게 맞지 않습니다. 이것은 내 수업을위한 코드입니다 :'class ProfileViewController : UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout' 그것은 UIViewController 유형인지 확인하거나 UICollectionViewController 여야합니까? 이것이 문제가되지 않는다면 다른 아이디어가 있습니까? –

1

당신이 기능에 UICollectionViewDelegate을 시도 할 수 enter image description here

현재 클릭의 요소를 얻을 수 indexPath을 사용할 수 있습니다; navigationController가 없으면 navigationViewController가 있어야하며, navigationController가 nil이면 프로토콜 또는 블록을 시도 할 수 있습니다. 죄송합니다, 제 영어 실력이 좋지 않습니다. 어쩌면 문법이 잘못되었을 수도 있습니다.

관련 문제