I'm having trouble creating custom table view cells in swift with Xcode6 (beta 4). More precisely I'm unable to access (unwrap) my custom UILabels inside the cell, since they never gets initialized.
Here's how I've got it all setup:
I've made a view in storyboard, which contains a table view with a prototype cell:
The view is hooked up to a class MyCoursesTableViewController, and the cell (with identifier courseCell) to CourseTableViewCell. I've pasted both classes below (with just the relevant bits of code):
MyCoursesTableViewController.swift
import UIKit
class MyCoursesTableViewController: NavToggleTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(CourseTableViewCell.self, forCellReuseIdentifier: "courseCell")
}
override func numberOfSectionsInTableView(tableView: UITableView!) -> Int {
return 1
}
override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell : CourseTableViewCell = tableView.dequeueReusableCellWithIdentifier("courseCell", forIndexPath: indexPath) as CourseTableViewCell
// cell is not nil
if let titleLabel = cell.titleLabel {
// never gets here
} else {
cell.textLabel.text = "Course Title"
}
return cell
}
}
The NavToggleTableViewController
class is just a common baseclass I use for all view controllers and doesn't affect the result.
CourseTableViewCell.swift
import UIKit
class CourseTableViewCell: UITableViewCell {
@IBOutlet weak var courseIcon: UIImageView!
@IBOutlet weak var teacherIcon: UIImageView!
@IBOutlet weak var studentsCountIcon: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var studentsCountLabel: UILabel!
@IBOutlet weak var teacherLabel: UILabel!
init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
Below is a picture of how I've configured the cell in the utilities pane (in storyboard):
The problem arise inside the function tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> CourseTableViewCell
when I want to access the UILabels. If I were to put something like cell.titleLabel.text = "Course Title"
I get the following error message:
fatal error: unexpectedly found nil while unwrapping an Optional value
Where am I doing things wrong? Would appreciate any help, thanks!