将数据从Tableview传递到CollectionView SWIFT

时间:2018-05-28 08:45:47

标签: ios 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()
    }
}

在我的collectionView

        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()
}

enter image description here

1 个答案:

答案 0 :(得分:1)

要从集合中删除项目,必须先从数据源中删除<​​/ p>

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

//

退休

let selected = users.index(of:chosenUser[indexPath.row])
相关问题