2017-03-25 29 views
-1

我有一個收集視圖,您可以點擊單元格放大圖像並點擊放大的圖像關閉它,在每個單元格上我也有一個可選複選標記,以便您可以選擇稍後下載選定的圖像。代碼幾乎可以工作,除了有時我必須選擇或取消勾選兩次。我真的不明白什麼即時消失,但這裏是我的代碼:點擊兩次以突出顯示收集視圖中的複選標記

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "photoCell", for: indexPath) as! PhotoCell 
    let tap = UITapGestureRecognizer(target: self, action: #selector(checkmarkWasTapped(_ :))) 

    cell.backgroundColor = .clear 
    cell.imageView.image = UIImage(contentsOfFile: imagesURLArray[indexPath.row].path) 
    cell.checkmarkView.checkMarkStyle = .GrayedOut 
    cell.checkmarkView.tag = indexPath.row 
    cell.checkmarkView.addGestureRecognizer(tap) 

    return cell 
} 

func checkmarkWasTapped(_ sender: UIGestureRecognizer) { 

    let checkmarkView = sender.view as! SSCheckMark 
    let indexPath = IndexPath(row: checkmarkView.tag, section: 0) 

    let imageURL = imagesURLArray[indexPath.row] 

    if checkmarkView.checked == true { 

     checkmarkView.checked = false 
     selectedImagesArray.remove(at: selectedImagesArray.index(of: imageURL)!) 
    } else { 

     checkmarkView.checked = true 
     selectedImagesArray.append(imageURL) 
    } 

    collectionView.reloadItems(at: [indexPath]) 
} 

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

    addZoomedImage(indexPath.row) 
    addGestureToImage() 
    addBackGroundView() 

    view.addSubview(selectedImage) 
} 

任何幫助將是偉大的。謝謝

回答

1

我相信你有一個問題,當你滾動集合視圖,集合視圖重新加載每個單元格,並且你沒有任何有關checkview的最新狀態的信息。

通常我會存儲一個bool數組(在collection視圖中的元素數量的大小,您可以在加載模型後輕鬆創建),所以每次用戶雙擊checkmark視圖時,我會更改採集視圖單元格的索引並更改布爾數組元素爲true。

var boolArray = [Bool]() 
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "photoCell", for: indexPath) as! PhotoCell 
    let tap = UITapGestureRecognizer(target: self, action: #selector(checkmarkWasTapped(_ :))) 

    cell.backgroundColor = .clear 
    cell.imageView.image = UIImage(contentsOfFile: imagesURLArray[indexPath.row].path) 

     if(boolArray[indexPath.row]){ 
      cell.checkmarkView.checked = false 
     } 
     else{ 
      cell.checkmarkView.checked = true 
     } 

    cell.checkmarkView.checkMarkStyle = .GrayedOut 
    cell.checkmarkView.tag = indexPath.row 
    cell.checkmarkView.addGestureRecognizer(tap) 

    return cell 
} 

這可能是一個醜陋的解決方案,但我相信它會工作。

+0

嗨,感謝您的回覆,您添加的if語句會不會在每次重新加載時交換選擇?是否應該說'如果!(boolArray [indexPath.row]){' – Wazza

+0

如果用戶在boolArray [indexPath.row]將爲false之前沒有爲單元格添加書籤,並且checkmarkView將在加載單元格時取消選中。否則它會被檢查。如果你的checkmarkView是這樣工作的? –

+0

如果我在viewdidload中用false填充bool數組並使用'ifif!(boolArray [indexPath.row])'它們都未被選中,但是當我選中該檢查並立即取消選中時,如果我使用if(boolArray [indexPath.row])',那麼他們都會被檢查,當我選擇它們時什麼都不會發生。 – Wazza

相關問題