簡體   English   中英

將數據從 Tableview 傳遞到 CollectionView SWIFT

[英]passing data from Tableview to CollectionView SWIFT

我試圖傳遞一個數據,每當我點擊用戶時,它都會顯示在 collectionView 上。 但是,我不知道為什么無論我單擊哪個 tableview 行,它都會添加我的頂級用戶,然后是第二個等等。我應該怎么做? (我的 collectionView 和 tableView 都在同一個視圖上)

我使用協議將數據從 tableview 發送到 collectionView

protocol toRefresh {
func updateCollectionView()  }

我聲明了一個變量來存儲選定的用戶:

var chosenUser: [User] = []

至於我的 tableView

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let user = users[indexPath.row]
    chosenUser.append(user)
    updateCollectionView()
    }
}

在我的收藏視圖中

        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return chosenUser.count
}

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

    self.collectionView.deleteItems(at: [indexPath])
    self.chosenUser.remove(at: indexPath.item) // here crashes as well
}


func updateCollectionView() {
    collectionView.reloadData()
}

在此處輸入圖片說明

要從集合中刪除一個項目,它必須首先從數據源中刪除

self.chosenUser.remove(at: indexPath.row)  
self.collectionView.deleteItems(at: [indexPath])

檢索

let selected = users.index(of:chosenUser[indexPath.row])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM