Getting Nil While Trying to Set Class Label Property | UITableView - ios

I keep getting unexpectedly found nil while unwrapping an Optional value when I run this code.
What I am trying to do is get the first property in an array of objects so I use .map to get the first property which is "workoutName"
Then I try to set the label in the CellData class to this value but keep getting that it found nil.
I appreciate all help I can get.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var workoutName = workouts.map { $0.workoutName }
let cell = CellData()
cell.workoutNameLabel.text! = workoutName[indexPath.row]
return cell
}
Cell Data Class
import UIKit
class CellData: UITableViewCell {
#IBOutlet weak var workoutNameLabel: UILabel!
#IBOutlet weak var numberOfSetsNumberLabel: UILabel!
#IBOutlet weak var numberOfRepsNumberLabel: 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
}
}

I would set class variable into CellData class and set it in awakeFromNib since awakeFromNib won't happen before the cellForRow is finished, so you can be almost 100% sure that the label will be nil.. try this:
import UIKit
class CellData: UITableViewCell {
//someLableValue string
var labelValueText: String?
#IBOutlet weak var workoutNameLabel: UILabel!
#IBOutlet weak var numberOfSetsNumberLabel: UILabel!
#IBOutlet weak var numberOfRepsNumberLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
workoutNameLabel.text = labelValueText
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
then you jsut set the variable labelValueText in cellForRowMethod in UITableViewController class

Related

UITableView with CustomCell not show data Swift4 on Xcode9

I read the other topics, but not solves my problem, I create a tableview and your cells with same value to make tests, but when I execute my project nothing data is showed. I put 5 size of rows to only to test. I don't know why my code not works.
My storyboard:
TableViewCellVenda.swift
class TableViewCellVenda: UITableViewCell {
#IBOutlet weak var cellView: UIView!
#IBOutlet weak var imageCloud: UIImageView!
#IBOutlet weak var labelValorTotal: UILabel!
#IBOutlet weak var labelQtdItens: UILabel!
#IBOutlet weak var labelCliente: UILabel!
#IBOutlet weak var labelDataVenda: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
ViewControllerVendas.swift
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// UI View
#IBOutlet weak var tableViewVendas: UITableView!
#IBOutlet weak var waitView: UIActivityIndicatorView!
// DB
var db: OpaquePointer?
var count : Int = 0
// Data
var saleOrders : [SaleOrder] = []
override func viewDidLoad() {
super.viewDidLoad()
self.waitView.startAnimating()
self.waitView.hidesWhenStopped = true
tableViewVendas.delegate = self
tableViewVendas.dataSource = self
}
// TableView
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellVenda") as! TableViewCellVenda
print("Cell for row")
cell.labelCliente.text = "Nome do Cliente"
cell.labelDataVenda.text = "14/02/1991"
cell.labelQtdItens.text = "20"
cell.labelValorTotal.text = "R$ 542,22"
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 75
}
}
Emulator:
Try adding a new swift UIKit file with a class of type UITableView and do all the tableview setup in there. And of coarse set the tables’s class as this UITableView class.

"fatal error" when calling tableView.reloadData(), the tableView is properly connected

I am trying to dynamically update a tableView while the program is running. I believe I have updated the array that the data loads from correctly, but when I press the button that calls self.eventTable.reloadData() I receive the error:
fatal error: unexpectedly found nil while unwrapping an Optional value
Here is the relevant code:
View Controller:
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
//Timer view
#IBOutlet weak var playButton: UIBarButtonItem!;
#IBOutlet weak var pauseButton: UIBarButtonItem!;
#IBOutlet weak var refreshButton: UIBarButtonItem!;
#IBOutlet weak var timerLabel: UILabel!
var counter = 0
var timer = Timer()
var isTimerRunning = false
//testing view container
var viewShowing = 1;
override func viewDidLoad() {
// Do any additional setup after loading the view, typically from a nib.
pauseButton.isEnabled = false
hideAll();
self.basicContainer.isUserInteractionEnabled = true;
self.basicContainer.isHidden = false;
self.timerLabel.text = String("00:00:00");
eventTable.dataSource = self
eventTable.delegate = self
super.viewDidLoad()
loadEvents(event: "timer start")
}
...
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Add table to keep track of events
#IBOutlet weak var eventTable: UITableView!
var eventData = [Session]()
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return eventData.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier") as! eventTableViewCell
let event = eventData[indexPath.row]
cell.eventLabel.text = event.session
return cell
}
private func loadEvents(event: String) {
guard let event1 = Session(session: event) else {
fatalError("Unable to instantiate event")
}
eventData += [event1]
DispatchQueue.main.async() {
self.eventTable.reloadData()
}
}
func testPrint() {
loadEvents(event: "testing cell adding")
//self.eventTable.reloadData()
viewWillAppear(false)
print("This is a test print");
}
}
The function works fine when it is called in ViewDidLoad(), but not when it is called by the button in another class ("This is a test print" prints to console so I know the button call is going through).
Expected behavior is the tableView (eventTable) reloading showing two cells, "timer start" and "testing cell adding" (ideally with "testing cell adding" being at the top).
Also want to emphasize that eventTable is connected to the storyboard, which seems to be a common problem on here.
Here is the Session.swift file and the eventTableViewCell.swift file if those are helpful:
Session.swift
import Foundation
import UIKit
class Session {
//MARK: Properties
var session: String
//MARK: Initialization
init?(session: String) {
guard !session.isEmpty else {
return nil
}
self.session = session
}
}
eventTableViewCell.swift
import Foundation
import UIKit
class eventTableViewCell: UITableViewCell {
//MARK: Properties
#IBOutlet weak var eventLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
Thanks!
Edit: The ViewController from where I call testPrint().
import UIKit
class BasicViewController: UIViewController {
var VC = ViewController();
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Basic buttons
#IBOutlet weak var warmButton: UIButton!
#IBOutlet weak var dryButton: UIButton!
#IBOutlet weak var stimulateButton: UIButton!
#IBOutlet weak var controlButton: UIButton!
#IBOutlet weak var bedButton: UIButton!
#IBOutlet weak var tempButton: UIButton!
#IBOutlet weak var pulseButton: UIButton!
#IBOutlet weak var ecgButton: UIButton!
#IBOutlet weak var apgarButton: UIButton!
#IBOutlet weak var helpButton: UIButton!
//APGAR options
#IBOutlet weak var skinColor: UIButton!
#IBOutlet weak var pulse: UIButton!
#IBOutlet weak var grimace: UIButton!
#IBOutlet weak var flexion: UIButton!
#IBOutlet weak var respiratoryEffort: UIButton!
#IBAction func warmButton(sender: AnyObject) {
VC.testPrint();
}
}
It would seem that you are all right in stating that I am instantiating a new ViewController which is causing the issue. How should I go about fixing this? Fairly new to Swift
I think, your problem is in this lines of codes:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier") as! eventTableViewCell
let event = eventData[indexPath.row]
cell.eventLabel.text = event.session
return cell
}
Can you check the cell identifier is same as your cell identifier
And number of rows in eventData array

UITableView doesn't fill custom cells inside of UITabBarController

I have UITabBarController and on one of the tabs I have UIViewController with UITableView inside.
I had created custom cell class.
If I fill tableView custom cells without UITabBarController (I put entry point to UIViewController) everything works fine, but if I use UITabBarController firstly, my cells are not populated with any data when I reach UITableView tab.
Where could be a bug here?
import UIKit
class blaViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView:UITableView, numberOfRowsInSection section:Int) -> Int {
return 3
}
func tableView(tableView:UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! blaTableViewCell
cell.myLabel.text = "123"
return cell
}
}
import UIKit
class blaTableViewCell: UITableViewCell {
#IBOutlet weak var myLabel: 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
}
}
Try tick install checkbox for all the constraints, not only wh wr. It worked for me. It is also described here: https://stackoverflow.com/a/32052154/2064500
#IBOutlet weak var myLabel: UILabel!
Try to do strong variable
#IBOutlet var myLabel: UILabel!

Swift customize table view cell unresolved identifier

I want to customize a table view cell, so I created a new file like the following and did necessary steps mentioned in https://developer.apple.com/library/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson7.html
DetailTableViewCell.swift:
import UIKit
class DetailTableViewCell: UITableViewCell {
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var contentLabel: 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
}
}
But when I write var details =Detail(), it will report Use of unresolved identifier 'Detail'.
WHY? I just follow the tutorial.
class CurrentViewController: UIViewController{
var details=[Detail]()
...
}
You did not define Detail model object.
You have to work with this first:

I got the UITableViewCell, but cell's elements are nil. Why?

The following code is a cleansed & rehashed version of a previous post.
ref: This class is not key value coding-compliant for the key...why?
import Foundation
import UIKit
var x = 1
struct DiaryItem {
var title:String?
var subTitle:String?
var leftImage:UIImage?
var rightImage:UIImage?
init(title:String, subTitle:String) {
self.title = title
self.subTitle = subTitle
}
}
class DiaryTableViewCell: UITableViewCell {
#IBOutlet weak var TitleLabel: UILabel!
#IBOutlet weak var SubTitleLabel: UILabel!
#IBOutlet weak var leftImageView: UIImageView!
#IBOutlet weak var rightImageView: UIImageView!
}
class DiaryTableViewController: UITableViewController {
let kCellIdentifier = "DiaryCell"
var diaryCell:DiaryTableViewCell?
var objects = NSMutableArray() //...global var.
override func viewDidLoad() {
self.title = "My Diary"
tableView.registerClass(DiaryTableViewCell.self, forCellReuseIdentifier: kCellIdentifier)
}
// -----------------------------------------------------------------------------------------------------
// MARK: - UITableViewDelegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let controller = gStoryboard.instantiateViewControllerWithIdentifier("DiaryPlayerVC") as DiaryPlayerViewController
self.navigationController?.pushViewController(controller, animated: true)
}
// -----------------------------------------------------------------------------------------------------
// MARK: - UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
// -----------------------------------------------------------------------------------------------------
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
// -----------------------------------------------------------------------------------------------------
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as DiaryTableViewCell?
// cell?.selectionStyle = .None
println("\(x++)) Inside cell")
cell!.TitleLabel?.text = "Hello"
cell!.TitleLabel?.backgroundColor = UIColor.blueColor()
cell!.SubTitleLabel?.text = "World"
cell!.contentView.backgroundColor = UIColor.redColor()
return cell!
}
...
}
I'm getting the cell, but no elements of that cell.
1) Inside cell
(lldb) po cell!.TitleLabel
nil
I cleaned up the code, it compiles & runs okay. The cell is loaded and painted with red so I can see it was loaded. But none of the cell's contents are instantiated.
why?
It's seeing the members of the cell now...
But now I'm getting:
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSObject 0x7f9691594810> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key leftImageView.'
If I disconnect the outlets, I get the images:
I've added the required init() but still have the same problem:
class DiaryTableViewCell: UITableViewCell {
#IBOutlet weak var leftImageView: UIImageView!
#IBOutlet weak var rightImageView: UIImageView!
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var subTitleLabel: UILabel!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
NSLog("init coder")
}
}
You have declared your properties as implicitly unwrapped optionals, signing that your are sure they are not nil. Thus there is no need to use optional chaining.
And please use lower case property names because upper case names are used for class names:
class DiaryTableViewCell: UITableViewCell {
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var subTitleLabel: UILabel!
#IBOutlet weak var leftImageView: UIImageView!
#IBOutlet weak var rightImageView: UIImageView!
}
Then try this:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as? DiaryTableViewCell {
// cell.selectionStyle = .None
println("\(x++)) Inside cell")
cell.titleLabel.text = "Hello"
cell.titleLabel.backgroundColor = UIColor.blueColor()
cell.subTitleLabel.text = "World"
cell.contentView.backgroundColor = UIColor.redColor()
return cell
}
return UITableViewCell()
}
If that crashes there must be something wrong with your outlet bindings.
Did you set your DiaryTableViewCell as the class for the nib in InterfaceBuilder?
Your tableCellClass lacks the awakeFromNib()method for nib:
class DiaryTableViewCell: UITableViewCell {
#IBOutlet weak var TitleLabel: UILabel!
#IBOutlet weak var SubTitleLabel: UILabel!
#IBOutlet weak var leftImageView: UIImageView!
#IBOutlet weak var rightImageView: UIImageView!
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
}
}
I found the solution:
This class is not key value coding-compliant for the key...why?
Here's the repost:
I had linked the UI elements to the WRONG source:
Here's the result:

Resources