4

I'm trying to pass data from a ViewController to a custom UITableViewCell but it's not working. When I print data from ViewController.swift everything is in tact but when I print data from CustomCell.swift the array is empty. Here is my code:

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)
    }
}
1
  • 4
    The cell's init method runs before you set the data in the line, cell.data = data[indexPath.row], so, of course the data will print as nil there. The cell shouldn't be storing data anyway; that's not the job of a view. Commented Mar 8, 2015 at 3:28

2 Answers 2

1

You can perform that simply by using didSet closure, change your code to the following:

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

And from your ViewController pass the data:

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
}

And it should work

Sign up to request clarification or add additional context in comments.

Comments

0

in CustomCell.swift, you just have to set the content such as: UILabel, UIImage, etc.

Rather than explaining here the whole things, I think you better follow the tutorial here: http://www.ioscreator.com/tutorials/prototype-cells-tableview-tutorial-ios8-swift

if you have more time, this is the deeper one : http://www.raywenderlich.com/81879/storyboards-tutorial-swift-part-1

good luck! ^_^

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.