将数据从UITableViewCell传递到UIViewController

时间:2017-11-05 23:24:02

标签: swift pass-data

我有UITableViewCell并且我想使用didSet将indexPath.row编号发送到UIViewController,但是当我使用其他东西的值时(在UIViewController中)xcode给我一个错误,表示该值为nil错误:意外发现null在展开可选值时。 但是如果我在UIViewController中的变量中打印,则会出现该值。 我所做的?感谢。

class TableViewCellCentral: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource  {


@IBOutlet weak var CollectionData: UICollectionView!


var send = Int() {
    didSet{

        ViewController().reload = send

        }
}


override func awakeFromNib() {
    super.awakeFromNib()

    CollectionData.dataSource = self
    CollectionData.delegate = self

    CollectionData.reloadData()
}


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


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

    cell.LabelData.text! = "number \(indexPath.row)"

    return cell
}



func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = CollectionData.dequeueReusableCell(withReuseIdentifier: "CellData", for: indexPath) as! CollectionViewCellData

    send = indexPath.row

    CollectionData.reloadData()

}


}

2 个答案:

答案 0 :(得分:0)

ViewController()只是ViewController的一个实例。当你说ViewController()时,你正在做的是创建一个新的ViewController,而不是访问你正在寻找的那个。如果你想要indexPath.row,你需要将它发送到实际的VC,而不仅仅是它的实例。

答案 1 :(得分:0)

您需要记住,并非所有数据都会立即加载,同时也不会始终按照您期望的顺序加载。您甚至可能在分配数据之前询问数据。尝试

import UIKit
class TableViewCellCentral: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource  {


@IBOutlet weak var CollectionData: UICollectionView!


var send = Int() {
    didSet {
        ViewController().reload = send
    }
}

override func awakeFromNib() {
    super.awakeFromNib()

    CollectionData.dataSource = self
    CollectionData.delegate = self
    CollectionData.reloadData()
}

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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = CollectionData.dequeueReusableCell(withReuseIdentifier: "CellData", for: indexPath) as! CollectionViewCellData
    if indexPath.row != nil {
        cell.LabelData.text! = "number \(self.indexPath.row)"
    }
    return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = CollectionData.dequeueReusableCell(withReuseIdentifier: "CellData", for: indexPath) as! CollectionViewCellData
    send = indexPath.row
    CollectionData.reloadData()
   }
}

我只是打印,如果值不是零!如果您有更多问题,请告诉我,或者如果我的解决方案无效,请告知我们。 =)

相关问题