【问题标题】:change tableview cell content on collection view cell selection在集合视图单元格选择上更改表格视图单元格内容
【发布时间】:2019-06-20 06:27:39
【问题描述】:

我在一个视图控制器中有一个tableViewcollectionView

tableView 我有标题描述,在collectionView 我有lable

我想对collectionView标签选择tableView内容应该改变。

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


func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionViewBookmark.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! BookMarkCollectionViewCell



    cell.lblTitle.text = Bookmark[indexPath.row]
    cell.backgroundColor = UIColor.white



    return cell
}


func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionViewBookmark.cellForItem(at: indexPath)

        cell?.backgroundColor = UIColor.blue

        self.selectedIndexPath = indexPath
//
        let newsDict = arrNewsData[indexPath.row]

        if (indexPath.row == 1)
        {
        let cell1 = tableViewBookMark.cellForRow(at: indexPath) as! BookMarkFirstTableViewCell
        cell1.lblTitle.text = newsDict["title"] as! String
        tableViewBookMark.reloadData()
        }
        tableViewBookMark.reloadData()
    }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableViewBookMark.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! BookMarkFirstTableViewCell

        let dict = arrNewsData[indexPath.row]


        cell.lblTitle.text = dict["title"] as! String
      // cell.imgBookMark.image = dict["image_url"]
        let url = URL(string: dict["image_url"] as! String)
        URLSession.shared.dataTask(with: url!) { (data, response, error) in
            if data != nil{
                DispatchQueue.main.async {
                    let image = UIImage(data: data!)
                    cell.imgBookMark.image = image
                }
            }
        }.resume()
         return cell
    }

【问题讨论】:

    标签: swift uitableview uicollectionview


    【解决方案1】:

    查看我的内联 cmets。

    var tempCell: BookMarkFirstTableViewCell?
    
    //Inside cellForRowAt indexPath
    
    tempCell = cell
    //Inside (collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
    
    tempCell.lblTitle.text = newsDict["title"] as! String
    

    【讨论】:

      【解决方案2】:

      更新单元格中的值后,您正在重新加载tableView

      tableViewBookMark.reloadData() 
      

      这将触发包括cellForRowAt 在内的数据源函数,因此您将丢失更新的值 解决此问题的方法是在UIViewController 中有一个全局变量,并在cellForRowAt 中检查其值并在其中更新它collectionView DidSelect

      额外提示:您无需重新加载所有 tableView 即可使用一次更改

      tableView.reloadRows(at: [indexPath], with: .top) 
      

      仅重新加载 tableView 中选定单元格的数量

      【讨论】: