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!
As explained in the last answer in UITableView Using Swift , it is an Xcode bug. Add the following:
override func tableView(tableView:UITableView!, heightForRowAtIndexPath indexPath:NSIndexPath)->CGFloat {
return 44
}
(or whatever height you want) and you'll be ok.
I duplicated your code and verified the solution.
Apologies, I forgot something else: you must not registerClass:forCellReuseIdentifier. This is already done when you set up your table and prototype cell in interface builder.
Sorry to reply after so much time has passed but I tear my hair on this exact problem this whole weekend. This bug is still there on XCode 8.3.2 (8E2002), this is the latest one as I write these lines. I had the exact same problem as the OP and adding
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 44
}
did not worked for me. The only thing that worked for me was removing this from my viewDidLoad:
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
// REMOVE THIS v v v v v
self.tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: "MyCustomCell")
// REMOVE THIS ^ ^ ^ ^ ^
// Do whatever you want hereā¦
}
The heightForRowAt indexPath is ineffective, you don't need to use it to fix it.
I hope this helped someone too !
Related
As far as I can tell, I have set up everything correctly (register and dequeue). However, when I try and access outlets in awakeFromNib(), I get
'Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value: file ....MechEntryCell.swift, line 18'
Which is weird, since other UITableViewCells doing similar things seem to work fine - and look identical to me.
The code failing:
class MechEntryCell: UITableViewCell {
#IBOutlet weak var mechName: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
mechName.text = "Hello" <<<<<<< CRASHES
}
func setDamageOption(_ damageOption: AdditionalDamageOption) {
mechName.font = UIFont.boldSystemFont(ofSize: mechName.font.pointSize)
mechName.text = damageOption.label <<<< WORKS FINE IF ABOVE CRASH REMOVED
}
}
which has a .xib file where the label has been correctly linked:
And I also register and dequeue:
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.register(UINib(nibName: MechEntryCell, bundle: nil), forCellReuseIdentifier: "MechEntryCell")
........
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tempDamageOptions.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: MechEntryCell.identifier) as? MechEntryCell {
cell.setDamageOption(tempDamageOptions[indexPath.item])
return cell
}
return UITableViewCell()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
Special Note:
When I set the label in the tableView(cellforRowAt:) method, then it works fine - so the IBOutlet DOES eventually link. What am I doing wrong?
Just want to add another example that might easily/accidentally happen to someone. In this case, had accidentally put the cell class on the ContentView, (rather then should have been left as simply UIView). In code, the cell's awakeFromNib was getting called twice. The first time the outlets were set, and in the second mysterious call, the outlets were nil.
I come back in shame with the solution.
somewhere during setup, I accidentally set the root view's custom class to that of the MechEntryCell. Removing this solved the issue.
I have a custom cell with some simple labels and a UIImage. Everything appears to be set correctly, and stepping through the debugger shows that everything is getting a value and even using the print in the debugger shows that the labels have text. However my table view is still empty when executed. I have been looking at this for too long and cannot figure out the problem.
Here is the cell code
class CurrentFileCell: UITableViewCell {
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var statusImage: UIImageView!
#IBOutlet weak var dateLabel: UILabel!
var currentContent: AircraftContent! {
didSet{
setStyles(Constants.appStyleSetting)
self.nameLabel.text = currentContent.contentName
self.dateLabel.text = currentContent.contentStatus
self.statusImage.image = UIImage(named: "color_label_circle_green")
}
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
private func setStyles(settings: StyleSettings) {
let tableFont = UIFont(name: settings.bodyFont, size: CGFloat(settings.tableFontSize))
nameLabel.font = tableFont
dateLabel.font = tableFont
// Text color
let tableFontColor = settings.tableFontColor
nameLabel.textColor = tableFontColor
dateLabel.textColor = tableFontColor
}
Here is the ViewController code with a tableview inside.
class CurrentFilesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var content: AircraftContent?
#IBOutlet weak var currentFiles: UILabel!
#IBOutlet weak var downloadingLabel: UILabel!
#IBOutlet weak var readyLabel: UILabel!
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
self.content = loadContent()
setStyles(Constants.appStyleSetting)
//self.tableView.reloadData()
// Do any additional setup after loading the view.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CurrentFileCell", forIndexPath: indexPath) as? CurrentFileCell
cell?.currentContent = content
return cell!
}
func loadContent() -> AircraftContent {
return (NSKeyedUnarchiver.unarchiveObjectWithFile(AircraftContent.ArchiveURL.path!) as? AircraftContent)!
}
private func setStyles(settings: StyleSettings) {
let titleFont = UIFont(name: settings.bodyFont, size: CGFloat(settings.titleFontSize))
let key = UIFont(name: settings.bodyFont, size: CGFloat(settings.tableFontSize))
currentFiles.font = titleFont
downloadingLabel.font = key
readyLabel.font = key
// Text color
let titleFontColor = settings.titleFontColor
currentFiles.textColor = titleFontColor
downloadingLabel.textColor = titleFontColor
readyLabel.textColor = titleFontColor
}
Here are some images showing the debug location where the cell is not empty, and also printing out the label which has a value, but isn't being shown during simulation.
http://imgur.com/a/dBkpe
This is an image showing the prototype cell. The cell has the correct class set as well as the identifier.
http://imgur.com/PKtFTeQ
Lastly another image showing that the prototype cell is linked to the labels within the CurrentFileCell.
http://imgur.com/nW0QUjM
Any help at all with this would be appreciated. I have tried recreating everything but continue to be stumped as it seems like everything is how it should be.
You have to implement the 'heightForRowAtIndexPath' method for the table view
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let height:CGFloat = 75
return height
}
You may consider registering the custom class as it does not appear that you did. You can do that by using the following code in the viewDidLoad of your View Controller.
tableView.registerClass(CurrentFileCell.self, forCellReuseIdentifier: "cell")
If you are using an external nib you will want to use registerNib instead like so:
tableView.registerNib(UINib(name:"ReplaceWithYourNibName", bundle: nil), forCellReuseIdentifier: "ReuseIdentifier")
Of course, replace ReplaceWithYourNibName and ReuseIdentifier with the appropriate values. In addition, if your nib is in a different bundle specify that instead of nil (nil defaults to the main bundle).
However, do not use both registerClass and registerNib as whichever one you call last will be used and they were designed to be mutually exclusive. Whenever you make a custom UITableViewCell you must use either of the two for it to work unless you have set it explicitly in the storyboard.
Also, you could instead, use prototype cells to define your custom cell, which would, I believe, automatically register the cell. But only if you did not use prototype cells make sure to use registerClass or registerNib.
Good luck! Hope this helps!
If your cell is a static cell, then you need to comment out these methods in UITableViewDataSource:
/* override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
} */
I had the same issue.
Data has values and cell rows are showing empty.
I figured it by adding
contentView.addSubview(titleLabel)
where cell values are being set.
I have a table view with a custom cell build in it, the custom cell has two labels and one textfield. When the user edits the textfield then the label2 changes in the current cell. But I want that the value(Label2) in the second cell will also change based on the value in the current cell. Example: Value in the first cell is x, the Value in the second cell should be 2+x. How should I realize that? In my view controller I am using the following code:
var myString = [String]()
#IBOutlet weak var TableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
myString = ["a", "b"]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myString.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CalculationsTableViewCell
tableView.tableFooterView = UIView(frame: CGRectZero) //hide empty cells in UITableView
cell.Label?.text = myString[indexPath.row]
return cell
}
My TableViewCell:
#IBOutlet weak var Label: UILabel!
#IBOutlet weak var Label2: UILabel!
#IBOutlet weak var TextField: UITextField!
#IBAction func TextFieldEditingChanged(sender: AnyObject) {
var value: Double
value = NSString(string: TextField.text!).doubleValue
Label2.text = "\(value)"
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
Firstly you should / could make use of the delegate pattern to communicate from the cell back to your controller:
create a protocol with a method named e.g. userEnteredNumber
let your view controller conform to that protocol
create a field in the TableViewCell called delegate - its type should the previously created protocol
when setting up the cell in cellForRowAtIndexPath assign self to the delegate property of the cell
as soon as the user enters a value call the delegate method on the previously set delegate
Secondly you have to somehow remember the state of your application. The thing with tableviews is that the iOS can decide to reload the contents of the tableView at any point (theoretically) and your controller has to keep track of the exact content each cell should have.
I do not know what the exact requirements are for your app but you should probably assign the value that gets transmitted via the protocol method to some variable in your viewController. Then you trigger a tableView reloadData and finally you have to alter the cellForRowAtIndexPath method to set the desired properties of some of the cells based on the stored value.
I have tried everything possible but I still can't figure out why the data is not shown in a custom cell. It looks fine in a subTitle cell and println confirms the data is there. I have checked the identifier and the IBOutlets a 100 times:
// ActivityDetailsTableViewController.swift
// TestActForm
//
// Created by Jeremy Andrews on 2015/08/08.
// Copyright (c) 2015 Jeremy Andrews. All rights reserved.
//
import UIKit
class ActivityDetailsTableViewController: UITableViewController
{
var activities: [Activity] = activityProfile
override func viewDidLoad()
{
super.viewDidLoad()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return activities.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
-> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("ActivityDetail", forIndexPath: indexPath) as! ActivityDetailCell
let activity = activities[indexPath.row] as Activity
println(activity.question)
cell.questionLabel?.text = activity.question
cell.answerLabel?.text = activity.answer
println(cell.questionLabel.text)
return cell
}
}
import UIKit
class ActivityDetailCell: UITableViewCell
{
#IBOutlet weak var questionLabel: UILabel!
#IBOutlet weak var answerLabel: UILabel!
override func awakeFromNib()
{
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool)
{
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
Thanks to everyone who gave suggestions - after 2 days struggle I finally found the solution thanks to: creating custom tableview cells in swift.
All you have to do is go to file inspector - uncheck size classes - there will be warnings etc.run and there is the data - strangely - go back to file inspector and check "use size classes" again, run and all data correctly reflected. Seems like in some cases the margin is set to negative.
A thought - if println( cell.nameLabel.text) shows your data is there then it is, check margin or put labels in the centre as a trial.
I noticed before that the story board had a highlighted area that did not match the cell boundaries - this actually showed the boundaries that run would use. A bug I think
Use a breakpoint in cellForRowAtIndexPath and check cell, outlets, model.
Also check if you set the delegate, datasource and outlet for the table.
cell.questionLabel?.text = activity.question
cell.answerLabel?.text = activity.answer
this code would fail silently if these label are not created. I bet you did not hook them up via IBOutlets in your storyboard.
I've been stuck with this problem for days, so I'd be really happy if someone could help.
I'm trying to create a dynamic UITableView, for which I created a custom UITableView subclass and I've created a custom UITableViewCell subclass as well, because I need several UILabels and a UIButton in each cell.
The cell is created, but the problem is that the value of the labels is always nil, hence the cell isn't displayed properly.
This is, how the storyboard looks like, and this is what I see while running the program.
Here's my UITableViewCell subclass:
import UIKit
class QuestionTableViewCell: UITableViewCell {
#IBOutlet var student: UILabel!
#IBOutlet var labDesk: UILabel!
#IBOutlet var topic: UILabel!
#IBOutlet var answers: UILabel!
}
and my UITableView subclass:
import UIKit
class QuestionViewController: UITableViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var table: UITableView!
struct Question {
var student: String
var labDesk: String
var topic: String
var answered: String
}
override func viewDidLoad() {
super.viewDidLoad()
table.estimatedRowHeight = 50
table.dataSource = self
table.delegate = self
self.table.registerClass(QuestionTableViewCell.self, forCellReuseIdentifier: "cell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
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 {
let cell = tableView.dequeueReusableCellWithIdentifier("cell") as QuestionTableViewCell
cell.student.text = "random string"
cell.labDesk?.text = "25/A"
cell.topic?.text = "string"
cell.answers?.text = "3"
return cell
}
}
Try removing self.table.registerClass(QuestionTableViewCell.self, forCellReuseIdentifier: "cell")
If you're using a cell with a nib then make sure that you are registering the cell with the table view using registerNib:forCellReuseIdentifier:. If the cell just has a class then use registerClass:forCellReuseIdentifier:.
First, you don't have to register the class if it exists in Interface Builder.
Second, you should dequeueReusableCellWithIdentifier:forIndexPath instead of dequeueReusableCellWithIdentifier.
Third, UITableViewController already has a property called tableView so there is no need to make an IBOutlet to table as UITableViewController already handles this. It also conforms to the UITableViewDataSource and UITableViewDataSource so these are extraneous.
Fourth, don't set the properties for table set them for tableView.
Fifth, cell.labDesk.text = "" is sufficient, no need to make it optional.
If all your IBOutlets are hooked up, Cell Identifiers correctly set, and these revisions are made, it will work.
class QuestionTableViewCell: UITableViewCell {
#IBOutlet var student: UILabel!
#IBOutlet var labDesk: UILabel!
#IBOutlet var topic: UILabel!
#IBOutlet var answers: UILabel!
}
class QuestionViewController: UITableViewController {
struct Question {
var student: String
var labDesk: String
var topic: String
var answered: String
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = 50
tableView.dataSource = self
tableView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
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 {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as QuestionTableViewCell
cell.student.text = "random string"
cell.labDesk.text = "25/A"
cell.topic.text = "string"
cell.answers.text = "3"
return cell
}
}
The most important part is to register the xib containing the custom cell with the table view. Therefore add the following code in viewDidLoad() method.
let nib = UINib.init(nibName: "MyCustomCell", bundle: nil)
self.tblUsers.register(nib, forCellReuseIdentifier: "MyCustomCell")
I might be late here, but I just solved a similar problem.
Make sure you've set the Identifier in InterfaceBuilder on your UITableViewCell.
For those who are still trying to figure this out after trying all those possible solutions:
Disconnect/Reconnect the IBOutlets in your Storyboards should do the trick!
Don't forget to add:
tableView?.register(UINib(nibName: "xyz",
bundle: nil),
forCellReuseIdentifier: "abc")
If you are using a table cell with Xib. you need to register your cell with ..
register(_:forCellReuseIdentifier:)
If you haven't added constraints for the label then they will not be created though the custom cell is created.
Make sure you added some constraints.
Make sure that the selected cell is in the right "module" and if necessary, inherit:
If not, your IBOutlets will be nil.
Issue I was facing: TableViewCell has been created and all the IBOutlets are nil. So I can't set any values such as text or color etc. Below code worked for me.
Xcode version: 13.3
Step 1:
Remove datasource and delegate reference form storyboard.
Step 2:
In viewDidLoad add,
tableView.delegate = self
tableView.dataSource = self
Step 3:
In tableview UITableViewDataSource cellForRowAt function, add your cell the given way.
let cell = tableView.dequeueCell(ofType: YourCellName.self)
cell.yourCellFunction()
return cell
Note 1: dequeueCell(ofType...) is calling the below function internally. you don't need to use it directly.
func dequeueCell<T: UITableViewCell>(ofType type: T.Type) -> T {
}
Important: You don't need to provide any "Resporation ID" or "Reuse Identifier" for cell. It works with your cell name.