iOS/iOS Swift 개발 일기

iOS swift addGestureRecognizer 클릭시 UILabel 색상 변화

Developer-Michelle 2022. 10. 19. 23:28

런칭한 앱 업데이트 중 기록

-collectionview에서 collectionview 클릭시 해당 contentview에 있는 placeLabel 색상이 검정->textcolor로 바뀌면서 화면 전환.

 

ShopVC.swift

 

//클릭할 때 색깔이 칠해지는 부분 인식하기 위해서 일단 선언 nil, 0, 1, 2, ...

var selectedIndexPath: IndexPath!

 

//collectionview에 tap했을때 감지하는걸 달아줌

override func viewDidLoad() {

 collectionView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didTouchDown(gestureRecognizer:))))

}

 

//collectionview 클릭을 해서 화면전환 후 다시 해당 뷰로 넘어올 때: 색깔 다시 원래 블랙으로 지정. 

override func viewWillAppear(_ animated: Bool) {

        if selectedIndexPath != nil {

            (collectionView.cellForItem(at: selectedIndexPath) as? ShopCollectionViewCell)!.placeLabel.textColor = .black

        }

    }

 

 

collectionview - didSelectItemAt 코드는 필요 없어졌다. 원래 여기 메소드에 썼던 화면 전환도 아래 코드에서 씀.

 

    @objc func didTouchDown(gestureRecognizer: UITapGestureRecognizer) {

        let location = gestureRecognizer.location(in: gestureRecognizer.view)

        let collectionView = gestureRecognizer.view as! UICollectionView

        if let indexPath = collectionView.indexPathForItem(at: location) {

            selectedIndexPath = indexPath

            (collectionView.cellForItem(at: indexPath) as? ShopCollectionViewCell)!.placeLabel.textColor = Constants.BaseColor.pointcolor

                let vc = ProductViewController()

                vc.section_name = self.list[indexPath.item]

                self.navigationController?.pushViewController(vc, animated: true)

        }

    }