0

항목을 표시하려면 가로 수집을 사용하고 있습니다. 사용자가 항목을 선택/선택 해제 할 때 텍스트 아래에 흰색 테두리를 추가/제거 할 때. 여기 자동으로 처음 항목로드

내가 콜렉션 뷰의 첫 번째 항목은 내가 코드를 시도

(밑줄)을 bottomLayer로로드해야합니다로드 할 때

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

    if let cell = collectionView.cellForItem(at: indexPath) { 

     if cell.isSelected { 

      bottomLayer.frame = CGRect(x: 0, y: (cell.frame.height) - 7, width: (cell.frame.width), height: 3) 
      bottomLayer.backgroundColor = UIColor.white.cgColor 
      cell.layer.addSublayer(bottomLayer) 
     } 
    } 
} 


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

    if collectionView.cellForItem(at: indexPath) != nil { 

      bottomLayer.backgroundColor = UIColor.green 
    } 
} 

내가 원하는 것은 코드입니다

let indexPathForFirstRow = IndexPath(row: 0, section: 0) 
CollectionView.selectItem(at: indexPathForFirstRow, animated: true, scrollPosition: []) 


collectionView(CollectionView, didSelectItemAt: indexPathForFirstRow) 

하지만 작동하지 않습니다. 나는 많은 질문을했지만 대부분은 모두 동일한 해결책을 가지고 있으며 나의 경우에는 작동하지 않는다. 아무도 나 좀 도와 줄래?

답변

1

그런 다음, 버튼 액션에 CollectionView를로드 viewDidAppear에서

CollectionView.layoutIfNeeded() 
let indexPathForFirstRow = IndexPath(row: 0, section: 0) 
CollectionView.selectItem(at: indexPathForFirstRow, animated: true, scrollPosition: []) 
collectionView(CollectionView, didSelectItemAt: indexPathForFirstRow) 

전화를하는 경우 :

override func viewDidAppear(_ animated: Bool) { 
    let indexPathForFirstRow = IndexPath(row: 0, section: 0) 
    CollectionView.selectItem(at: indexPathForFirstRow, animated: true, scrollPosition: []) 
    collectionView(CollectionView, didSelectItemAt: indexPathForFirstRow) 
} 
+0

내가 버튼 액션 이벤트에 collectionview를로드하고 있습니다. 그래서 collectionview가로드 된 직후에이 코드를 추가했습니다. 그리고 그것은 didSelectItem 메서드를 발생시키지 만, 'cell = collectionView.cellForItem (at : indexPath)'의 경우 아무런 제안이 없으면 실패합니다. – iUser

+0

'CollectionView.layoutIfNeeded()'가 마술을했습니다! 고맙습니다. – iUser

관련 문제