본문 바로가기

UIKIT

collectionView.reloadData()는 어디에 넣을까? - 추가

각 스택뷰를 눌렀을 때 userCollectionView의 셀 배경색을 변경하려면, reloadData()를 호출하는 부분을 제스처 메서드에서 수행하는 게 맞습니다.

하지만, 현재 cellForItemAt에서 self.backgroundColor로 배경색을 설정하고 있으므로, 변경된 배경색 정보를 저장할 방법이 필요합니다. 예를 들어, ProfileViewController에 selectedColor라는 변수를 추가하여 선택된 색상을 저장하고, reloadData()를 통해 셀 배경을 업데이트할 수 있습니다.

 

    @objc func lampStackTapped() {
        self.selectedColor = .systemRed
        print("램프 탭")
        DispatchQueue.main.async {
            self.profileView.userCollectionView.reloadData()
        }
    }

    @objc func scrapStackTapped() {
        self.selectedColor = .systemCyan
        print("스크랩 탭")
        DispatchQueue.main.async {
            self.profileView.userCollectionView.reloadData()
        }
    }

    @objc func estimateStackTapped() {
        self.selectedColor = .systemMint
        print("리뷰 탭")
        DispatchQueue.main.async {
            self.profileView.userCollectionView.reloadData()
        }
    }

 

 

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if collectionView == profileView.userCollectionView {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
        
        // 선택된 색상으로 셀 배경색 설정
        cell.backgroundColor = selectedColor
        return cell
    }
    
    return UICollectionViewCell()
}

 

 

추가 팁:

reloadData()는 제스처 메서드에서 호출하는 것이 맞습니다. 이 방식이 선택된 색상을 즉시 반영할 수 있도록 해주기 때문입니다. cellForItemAt에서 직접 변경하는 대신 제스처 메서드에서 색상을 관리하는 것이 MVC 패턴에도 더 적합합니다.

 

 

 


 

Completion Handler를 사용하여 geRandomPage 함수가 실행되면 그 다음에 getRandomSpot()이 실행되게 했습니다. 

 

여기서 문제가 recommendSpotCollectionView.reloadData 시점이었습니다. 

원래는 getRandomSpot() 메서드에 넣었지만, 이럴 경우에 randomSpotArray를 다 받기도 전에 실행될 수 있어 
컬렉션뷰에 이미지가 안보일 수 있습니다. 

 

executeInOrder() 함수에서의 reloadData() 호출):

  • 이 경우, getRandomSpot()이 완료된 후, 메인 스레드에서 reloadData()를 명확히 호출하고 있습니다. 이 순서 보장 덕분에 데이터가 제대로 설정된 후 컬렉션 뷰를 리로드하므로 UI가 예상대로 작동합니다.
   func getRandomSpot() {
        NetworkManager.shared.fetchRandomAttractions { result in
            switch result {
            case .success(let item):
                self.randomSpotArray = item.response.body.items.item
//                DispatchQueue.main.async {
//                    self.exploreMainView.headerView.recommenSpotCollectionView.reloadData()
//                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    
    func getRandomPage(completion: @escaping (Result<Void, Error>) -> Void) {
        NetworkManager.shared.initailizeTotalPages { result in
            switch result {
            case .success():
                print("success")
                completion(.success(()))
            case .failure(let error):
                print(error.localizedDescription)
                completion(.failure(error))
            }
        }
    }
    
    // getRandomPage가 먼저 실행되고 그 뒤로 getRandomSpot이 실행되게 호출하는 메서드
    func executeInOrder() {
        getRandomPage { result in
            switch result {
            case .success():
                self.getRandomSpot()
                DispatchQueue.main.async {
                    self.exploreMainView.headerView.recommenSpotCollectionView.reloadData()
                }
            case .failure(let error):
                print("Failed to get random Item: \(error.localizedDescription)")
            }
        }
    }