Swift: IBoutlets are nil in Custom Cell

☆樱花仙子☆ 提交于 2019-12-17 20:22:41

问题


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
}

回答1:


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.)




回答2:


Pretty sure that you need to remove the line

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

from viewDidLoad().



来源:https://stackoverflow.com/questions/26411140/swift-iboutlets-are-nil-in-custom-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!