Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: IBoutlets are nil in Custom Cell

I can't figure out why this custom cell is not being output.

I have a custom cell set up in a storyboard (no nib). I have a text field and 2 labels which are nil when I try to access them in the custom cell class. I'm almost sure I have everything hooked up correctly, but still getting nil.

I've selected my table cell in the storyboard and set Custom Class to TimesheetTableViewCell I've also control clicked on the table and set the datasource and delegate to be TimesheetViewController

My custom cell class:

import UIKit

class TimesheetTableViewCell: UITableViewCell {

@IBOutlet var duration: UITextField!
@IBOutlet var taskName: UILabel!
@IBOutlet var taskNotes: UILabel!

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

override init?(style: UITableViewCellStyle, reuseIdentifier: String!) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    println("Cell's initialised")// I see this
    println(reuseIdentifier)// prints TimesheetCell
}


override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
}

func setCell(duration: String, taskName: String, taskNotes: String){
    println("setCell called")
    self.duration?.text = duration
    self.taskName?.text = taskName
    self.taskNotes?.text = taskNotes
}

My controller:

class TimesheetViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{

@IBOutlet var timesheetTable: UITableView!

var items = ["Item 1", "Item2", "Item3", "Item4"]

override func viewDidLoad() {
    super.viewDidLoad()
    self.timesheetTable.registerClass(TimesheetTableViewCell.self, forCellReuseIdentifier: "TimesheetCell")

}
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("TimesheetCell", forIndexPath: indexPath) as TimesheetTableViewCell
        println(items[indexPath.row]) // prints corresponding item
        println(cell.duration?.text) // prints nil
        cell.setCell(items[indexPath.row], taskName: items[indexPath.row], taskNotes: items[indexPath.row])
        return cell
}
like image 266
Sam Luther Avatar asked Oct 16 '14 18:10

Sam Luther


1 Answers

The problem is this line:

self.timesheetTable.registerClass(TimesheetTableViewCell.self, forCellReuseIdentifier: "TimesheetCell")

Delete it. That line says: "Do not get the cell from the storyboard." But you do want to get the cell from the storyboard.

(Make sure, however, that the cell's identifier is "TimesheetCell" in the storyboard, or you'll crash.)

like image 149
matt Avatar answered Nov 06 '22 16:11

matt