2016년 9월 14일 수요일

UICollectionView Cell checkbox 이슈 해결 @@ in Swift2.x - Xcode 7.3 iOS 9.3

이어서 지난 번 CheckBox 코딩의 이슈를 해결코자 한다.
[이슈 내용]
1. 선택된 체크박스가 중복되어 나타난다, 즉 아래로 스크롤 시 체크하지 않았던 체크박스도 체크가 된 상태로 나타나는 경우

2. 스크롤 후 다시 원위치 시 체크박스된 박스가 위치가 바뀌는 현상

일단 두가지 이슈의 공통점은 버튼마다 특정 값을 가지고 있지 않다는 것이다.
다시말해 몇번째 Cell의 Checkbox인지 확인이 어렵다는것이다.

그래서 CheckBox 클래스 값에 변수를 만들어 그 변수에
Cell의  indexPath.row 값을 넣기로 했다
------------------------------------------------------------------------------------------
class CheckBox: UIButton {
    // Images
    
    let checkedImage = UIImage(named: "photoSelect_active")! as UIImage
    let uncheckedImage = UIImage(named: "photoSelect_deactive")! as UIImage

    var tagCount: Int = 0
==========================================================================

------------------------------------------------------------------------------------------
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionCell", forIndexPath: indexPath) as! AlbumPhotoCollectionViewCell
       
        ...
          cell.checkBoxbutton.tagCount = indexPath.row
          
          ...
        return cell

    }
==========================================================================

이렇게 하면 일단 버튼 마다 특정 값을 가지게 할 수 있다.
하지만 이슈처리하는데 가장 풀리지 않았던 문제는 CheckBox 의 중복 되는 문제
하여 CheckBox 클래스 안에서 특정 값을 이용해 Check 표시를 하는 메소드를 만들어보기로 했다.
이렇게 하게 된 가장 큰 이유는 CollectionView 에서 Cell 이 화면에 나타날때마다 객체를 새로 생성
하게 됨을 알게 되었고 생성 될때마다 실행하는 함수를 넣게 될 경우 중복되는 문제를
해결 할 수 있을거라 생각 하였기 때문이였다

일단 tagCount 라는 변수를 이용해 Check 여부를 확인 하는 메소드를 CheckBox 클래스 안에 만들다
------------------------------------------------------------------------------------------
func checkdconform(){
        if GridPhotosHelper.collectionViewCellDic[tagCount] == nil {
            self.isChecked = false
        }else{
           self.isChecked = true
        }
    }
==========================================================================

GridPhotosHelper.collectionViewCellDic[tagCount] 이 값은 체크박스 클릭 시 
tagCount를 key 값으로 딕셔너리로 저장하도록 선언 해놓은 변수이다.
------------------------------------------------------------------------------------------

public struct GridPhotosHelper {

 static var collectionViewCellDic : Dictionary = [Int : Bool]()
...
}
==========================================================================

CheckBox 클래스 내 버튼 클릭 함수에 true, false 값에 따라 딕셔너리로 저장하거나 삭제하도록 코딩을 추가 해준다
------------------------------------------------------------------------------------------
 func buttonClicked(sender:UIButton) {
        print(tagCount)
        if(sender == self){
            if isChecked == true{
                isChecked = false
                GridPhotosHelper.collectionViewCellDic[tagCount] = nil   
            }else{
                isChecked = true
                GridPhotosHelper.collectionViewCellDic[tagCount] = true
            }
        }
    }
==========================================================================
끝으로 객체가 생성 될때마다 위 함수를 실행하도록 코딩을 추가한다
------------------------------------------------------------------------------------------
 func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionCell", forIndexPath: indexPath) as! AlbumPhotoCollectionViewCell
        
        
          cell.checkBoxbutton.tagCount = indexPath.row
          cell.checkBoxbutton.checkdconform()
          
     ...
        return cell

    }
==========================================================================

앱을 테스트 해보면 이슈들이 해결된것을 확인 할 수 있고 체크된 Checkbox 의  값들도
딕셔너리에 따로 저장된다.

댓글 없음:

댓글 쓰기

추천 게시물

애플 개발자 등록방법 2016년 5월 8일 기준!!

애플 개발자 등록 절차 1. 개발자 등록 페이지 이동    애플 개발자 로그인 > Account 페이지 이동 > 하단 영역 클릭 (이미지 참조)   >> Enroll 클릭 >> 무조건 승인!! ...