iOS/iOS Swift 문법

iOS Swift) didSet 사용 예시 (with tableview/ collectionview)

Developer-Michelle 2023. 2. 9. 16:48

iOS Swift) didSet 사용 예시 (with tableview/ collectionview)

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cellId = String(describing: MyCollectionViewCell.self)
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! MyCollectionViewCell
        
        cell.profileImg.image = UIImage(systemName: systemImageNameArray[indexPath.item])
        cell.profileLabel.text = systemImageNameArray[indexPath.item]
        
        return cell
    }

 

위와 같이 ViewController에서 썼던 내용을

아래와 같이 CollectionViewCell 안에서 값 변경에 대해 didSet으로 적어두고,

 

var imageName: String = "" {
        didSet {
            print("MyCollectionViewCell / imageName - didSet() : \(imageName)")
            profileImg.image = UIImage(systemName: imageName)
            profileLabel.text = imageName
        }
    }

 

다시 ViewController로 돌아가서 아래와 같이 적어주면 맨 위의 코드 블록과 동일한 효과를 나타낸다.

 

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cellId = String(describing: MyCollectionViewCell.self)
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! MyCollectionViewCell
        
        cell.imageName = systemImageNameArray[indexPath.item]
        
        return cell
    }

'iOS > iOS Swift 문법' 카테고리의 다른 글

String(describing: ) 사용 예시  (0) 2023.02.09
iOS swift) if 구문에서 마지막 else, else if 생략 가능.  (0) 2022.08.31
if - let, guard - let  (0) 2022.08.30
프로퍼티와 메서드  (0) 2022.07.31
iOS swift 함수  (0) 2022.07.17