iOS Swift:如何将数据从ViewController传递到UITableViewCell

4
我将尝试将ViewController中的数据传递给自定义的UITableViewCell,但是它没有生效。当我从ViewController.swift打印data时,一切都正常,但是当我从CustomCell.swift打印data时,数组为空。这是我的代码:
ViewController.swift
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as! CustomCell
    cell.data = data[indexPath.row]
    return cell
}

CustomCell.swift

class CustomCell: UITableViewCell {
    var data = [CKRecord]()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        println(data)
    }
}

4
cell的初始化方法在您设置行中的数据之前运行,即cell.data = data[indexPath.row],因此,在那里打印出来的数据肯定是空的。无论如何,cell不应该存储数据;这不是视图的工作。 - rdelmar
2个回答

1

您可以通过使用 didSet 闭包来简单地执行此操作,将您的代码更改为以下内容:

class CustomCell: UITableViewCell {
    
    var data = [Int]() {
        didSet{
            print(data)
        }
    }
    
    var id: Int {
        didSet{
            loadById(id)
        }
    }

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        // This block runs before data being set! Rather call your code from didSet{} closure..
    }
    
    
    func loadById(_ id: Int) {
        // Your code goes here
    }
    
}

从您的 ViewController 传递数据:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
    let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! CustomCell
    
    cell.data = data[indexPath.row]
    
    cell.id = 1 // pass here any variable you need
    
    return cell
}

"而且它应该工作,保留HTML,不要解释。"

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接