SSRadiobuttonsController button found nil while unwrapping - swift

Hi I'm trying to add radiobuttons to my tableview. I have a tableviewcell class connected to the button in the tableview but when I try to add the button inside cellForRowAt indexpath function the app crash with error: unexpectedly found nil while unwrapping an Optional value
TableViewCell Code
import UIKit
class TableViewCell: UITableViewCell, SSRadioButtonControllerDelegate {
#objc func didSelectButton(selectedButton: UIButton?) {
NSLog(" \(selectedButton)" )
}
#IBOutlet var radioButton: UIButton!
#IBOutlet var taskText: 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
}
TableViewController Code
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
self.title = "Today"
//Radio buttons
radioButtonController.delegate = self
radioButtonController.shouldLetDeSelect = true
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = TableViewCell(style: .default, reuseIdentifier: "Cell")
let task = tasks[indexPath.row]
radioButtonController.addButton(cell.radioButton)
if let myName = task.name {
cell.textLabel?.text = myName
}
return cell
}

Related

DidSelectRow function is not called

I'm trying to implement the didSelectRow function and perform a segue but when running the cells select and nothing happens.
I created a print statement that also doesn't run which proves that the function doesn't appear to be firing. Why would this be?
I have checked the identifier is correct and have researched these for a few hours going through many stack overflow threads but with little luck.
import UIKit
import CoreData
class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let viewController = ListNameViewController()
let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext
var itemChoosen = 0
override func viewDidLoad() {
super.viewDidLoad()
homeListsTableView.delegate = self
homeListsTableView.dataSource = self
viewController.loadList()
}
#IBOutlet weak var homeListsTableView: UITableView!
#IBAction func templatesButton(_ sender: Any) {
tabBarController?.selectedIndex = 2
}
#IBAction func allListsButton(_ sender: Any) {
tabBarController?.selectedIndex = 0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewController.listName.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let result = viewController.listName[indexPath.row]
cell.textLabel?.text = ("\(String(result.listName!))")
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
context!.delete(viewController.listName[indexPath.row])
viewController.listName.remove(at: indexPath.row)
viewController.saveList()
homeListsTableView.reloadData()
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "items2", sender: self)
print("selected")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(false)
viewController.loadList()
homeListsTableView.reloadData()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
homeListsTableView.reloadData()
}
}
ListNameViewController:
import UIKit
import CoreData
class ListNameViewController: UIViewController, UITableViewDelegate {
let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext
var listName : [ListName] = []
override func viewDidLoad() {
super.viewDidLoad()
createButtonChange.isEnabled = false
//Objective-C Line used to keep checking if the text field is vaild before enabling the submit button
listNameValue.addTarget(self, action: #selector(textValidation), for: UIControl.Event.editingChanged)
}
#IBOutlet weak var listNameValue: UITextField!
#IBOutlet weak var locationOption: UITextField!
#IBOutlet weak var createButtonChange: UIButton!
#objc func textValidation() {
//Text Field Validation check before button is enabled
if listNameValue.text!.isEmpty {
createButtonChange.isEnabled = false
} else {
createButtonChange.isEnabled = true
}
}
// Create a new List
#IBAction func createButton(_ sender: Any) {
let newList = ListName(context: context!)
newList.listName = listNameValue.text
saveList()
self.navigationController!.popViewController(animated: true)
viewWillAppear(false)
}
func saveList() {
do {
try context!.save()
} catch {
print("Error saving context \(error)")
}
}
func loadList() {
let request : NSFetchRequest<ListName> = ListName.fetchRequest()
do{
listName = try context!.fetch(request)
} catch {
print("Error loading categories \(error)")
}
}
//Pass data to the HomeViewController
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// let vc = segue.destination as! HomeViewController
}
}
// commented out core data and just used a normal array for testing.
Did you add segue in your storyboard for the tableview ? In this case the didSelect is not call but the prepare(for segue) of the tableview controller is called.
Ok solved it - There was a rouge tap gesture recognizer on the page. Removed it and works on one click. I have seen that if you wish to keep the gesture just add this line of code at the top of the function:
tap.cancelsTouchesInView = false
Took three days but I got there. Thanks for the help!

unable to save on/off state of a UITableViewCell?

there are two attributes 'time' and 'isOn' (string, bool) in the entity named 'Item'
in viewcontroller class I am able to give default condition to 'isOn' attribute (in savePressed function) which makes switchbtn.isOn = true and saves it in the data model for that particular 'time'
viewcontroller class :-
class ViewController: UIViewController {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
#IBOutlet weak var timePickerView: UIDatePicker!
#IBOutlet weak var timeLbl: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
timePickerView.setValue(UIColor.white, forKeyPath: "textColor")
dateFormat()
// Do any additional setup after loading the view.
}
#IBAction func savePressed(_ sender: UIBarButtonItem) {
let entity = Item(context: context)
entity.time = timeLbl.text
entity.isOn = true
saveData()
self.dismiss(animated: true, completion: nil)
}
#IBAction func cancelPressed(_ sender: UIBarButtonItem) {
self.dismiss(animated: true, completion: nil)
}
#IBAction func valueChanged(sender:UIDatePicker, forEvent event: UIEvent){
dateFormat()
}
func saveData() {
(UIApplication.shared.delegate as! AppDelegate).saveContext()
}
func dateFormat() {
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm"
formatter.timeStyle = .short
timeLbl.text = formatter.string(from: timePickerView.date)
}
}
viewcontroller
in this class I am able to fetch and show the core data but don't know how to save the state of the cell switch button and update the data model as there is no use of 'didSelectRowAt' function
tableview class :-
class TableViewController: UITableViewController {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var items = [Item]()
override func viewDidLoad() {
super.viewDidLoad()
print(arr)
}
override func viewWillAppear(_ animated: Bool) {
getData()
tableView.reloadData()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) as! TableViewCell
cell.timeLbl.text = items[indexPath.row].time
cell.switchBtn.isOn = items[indexPath.row].isOn
return cell
}
func getData() {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
do {
items = try context.fetch(Item.fetchRequest())
}catch{
print("failed to get the data")
}
}
}
tableview
in this I am able to print the current state of the switch but cannot access the 'items[indexPath.row]' from the tableview class
cell class :-
class TableViewCell: UITableViewCell {
#IBOutlet weak var timeLbl: UILabel!
#IBOutlet weak var switchBtn: UISwitch!
var alarm = Bool()
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
}
#IBAction func valChange(_ sender: UISwitch) {
if sender.isOn{
switchBtn.isOn = true
}else {
switchBtn.isOn = false
}
}
}
In Swift the most efficient way is a callback closure.
In the cell add a property callback with a closure passing a Bool value and no return value. Call the callback when the value of the switch changed.
class TableViewCell: UITableViewCell {
#IBOutlet weak var timeLbl: UILabel!
#IBOutlet weak var switchBtn: UISwitch!
var alarm = Bool()
var callback : ((Bool) -> Void)?
#IBAction func valChange(_ sender: UISwitch) {
callback?(sender.isOn)
}
}
In cellForRow in the controller add the callback, in the closure update the model.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) as! TableViewCell
let item = items[indexPath.row]
cell.timeLbl.text = item.time
cell.switchBtn.isOn = item.isOn
cell.callback = { newValue in
self.items[indexPath.row].isOn = newValue
}
return cell
}
If cells can be inserted, deleted or moved you have to pass also the cell to get the actual index path
class TableViewCell: UITableViewCell {
#IBOutlet weak var timeLbl: UILabel!
#IBOutlet weak var switchBtn: UISwitch!
var alarm = Bool()
var callback : ((UITableViewCell, Bool) -> Void)?
#IBAction func valChange(_ sender: UISwitch) {
callback?(self, sender.isOn)
}
}
and
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) as! TableViewCell
let item = items[indexPath.row]
cell.timeLbl.text = item.time
cell.switchBtn.isOn = item.isOn
cell.callback = { currentCell, newValue in
let currentIndexPath = tableView.indexPath(for: currentCell)!
self.items[currentIndexPath.row].isOn = newValue
}
return cell
}

two sections and different three cells

1.I have one more section1
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1
}else{
return 3 //imageName.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var thirdCell = ThirdTableViewCell()
var cell = UITableViewCell()
var row2Cell = Row2TableViewCell()
if indexPath.row == 0 {
cell = tableView.dequeueReusableCell(withIdentifier: "Cell1", for: indexPath)
return cell
}else if indexPath.row == 1{
thirdCell = tableView.dequeueReusableCell(withIdentifier: "thirdCell", for: indexPath) as! ThirdTableViewCell
thirdCell.image1.image = #imageLiteral(resourceName: "plus")//imageArray[indexPath.row]
return thirdCell
}else{
row2Cell = tableView.dequeueReusableCell(withIdentifier: "Row2Cell", for: indexPath) as! Row2TableViewCell
return row2Cell
}
}
2.How did I get ThirdViewController.image
As I see you want to access ThirdViewController.image in your ThirdTableViewCell Class
this is how you can access instance of viewController (e.g Labels, Images and TextFeilds etc) in other View Controller or in custom class.
import UIKit
internal weak var AccessThirdViewController: ThirdViewController?
class ThirdViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
#IBOutlet weak var imageViewToChange: UIImageView!
override func viewDidLoad() {
AccessThirdViewController = self
}
it will make it accessible in all other viewControllers or classes
import UIKit
class ThirdTableViewCell: UITableViewCell {
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
}
#IBAction func onButtonClick(_ sender: Any) {
AccessThirdViewController?.imageViewToChange.image = UIImage(named: "rocket")!
}
}
Now you can simply access ThirdViewController directly using AccessThirdViewContoller
Or you can achieve this by using NotificationCenter as creating
NotificationCenter addObserver
Receive(Get) Notification and Function-Method handler for received Notification:
import UIKit
class ThirdViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
#IBOutlet weak var imageViewToChange: UIImageView!
override func viewDidLoad() {
NotificationCenter.default.addObserver(self, selector: #selector(setImage), name: Notification.Name("UpdateImage"), object: nil)
}
#objc func setImage(){
self.imageViewToChange.image = UIImage(named: "rocket")
}
Then Send(Post) Notification from ThirdTableViewCell Class on #IBAction of UIButton
import UIKit
class ThirdTableViewCell: UITableViewCell {
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
}
#IBAction func onButtonClick(_ sender: Any) {
NotificationCenter.default.post(name: Notification.Name("UpdateImage"), object: nil)
}
}

How to save the state of the checkbox to core data in Swift?

**I'm not a good English speaker. Please forgive me for my awkward English.
I'm working on a to do list project using checkbox. I cannot find a way to save the state of the checkbox to core data
This is a part of the code I use right now. Tasksis the Entity (class definition) and it has isMarked as a Boolean Attribute.
(I cut a lot to make it simple so if you find something strange in the code please write a comment)
import UIKit
import CoreData
var toDolist: [Tasks] = []
class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(toDoTable)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBOutlet weak var toDoTable: UITableView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return toDolist.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CustomTableViewCell
cell.box.setImage(#imageLiteral(resourceName: "uncheckedbox"), for: .normal)
let task = toDolist[indexPath.row]
return cell
}
func getData(){
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
do{
toDolist = try context.fetch(Tasks.fetchRequest())
}catch{
print("fetching failed")
}
}
override func viewWillAppear(_ animated: Bool) {
getData()
toDoTable.reloadData()
}
}
class CustomTableViewCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
#IBOutlet weak var box: CheckBox!
#IBOutlet weak var taskLbl: UILabel!
}
class CheckBox{
var isChecked: Bool = false{
didSet{
if isChecked == true{
self.setImage(#imageLiteral(resourceName: "checkedbox"), for: .normal)
}else{
self.setImage(#imageLiteral(resourceName: "uncheckedbox"), for: .normal)
}
}
}
override func awakeFromNib(){
self.addTarget(self, action: #selector(self.buttonClicked(_:)), for: .touchUpInside)
self.isChecked = false
}
func buttonClicked(_ sender: UIButton){
if sender == self{
if isChecked == true{
isChecked = false
}else{
isChecked = true
}
}
}
}
How can I solve this by adding some code to it? Or do I have to change all the code above?
Simple solution:
Remove the subclass of UIButton and revert the class of the button to UIButton.
In Interface Builder assign the images checkedbox and uncheckedbox to the button for states selected and default. The images are displayed automatically depending on the isSelected property of the button. That avoids completely to update the images in code.
The class CustomTableViewCell got the property task and the IBAction which must be connected to Touch Up Inside of the button. The property isSelected of the task must be changed to the name of the attribute of the NSManagedObject
class CustomTableViewCell: UITableViewCell {
#IBOutlet weak var box: UIButton!
#IBOutlet weak var taskLbl: UILabel!
var task : Tasks! {
didSet {
box.isSelected = task.isSelected
taskLbl.text = // update the label
}
}
#IBAction func buttonClicked(_ sender: UIButton)
{
let selected = !sender.isSelected
sender.isSelected = selected
task.isSelected = selected
// save the context if needed
}
}
In cellForRowAt just add the line to assign the task
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CustomTableViewCell
let task = toDolist[indexPath.row]
cell.task = task
return cell
}

Two UITableViews in one UIViewController with custom prototype cells gives errors

im learning swift and i am trying to build an app for logging workouts.
I'm using diefferent views and prototype cells and it works perfect.
But now on one view i have two tableviews, with each of them has the same kind of prototype cell, which is also a custom cell:
import UIKit
class muscleCell: UITableViewCell {
#IBOutlet weak var lblDescription: UILabel!
var id : Int64?
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
It has just an ID and a label. I have used it in another tableview and it works perfect.
I have found here on stackoverflow how to use multiple UITableViews in one View and it showed me the data perfectly with the standard cell.
But as soon as i add the identifier in the storyboard, and make the outlet connections and use these identifiers in the code i get an error.
a quick info, i have tried this line:
self.lvMainMuscles.register(UITableViewCell.self, forCellReuseIdentifier: "mainMuscleCell")
also like this (cause i found it somehwere that it might help):
self.lvMainMuscles.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
but did also not work.
import UIKit
class MachineController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var txtName: UITextField!
#IBOutlet weak var txtType: UITextField!
#IBOutlet weak var deleteToolbar: UIToolbar!
#IBOutlet weak var btnDelete: UIBarButtonItem!
#IBOutlet weak var lvMainMuscles: UITableView!
#IBOutlet weak var lvSupportingMuscles: UITableView!
var machineId: Int64?
var objMachine = Machine(connection: wpdb().db!)
var objMuscle = Muscle(connection: wpdb().db!)
var mainMuscleData : Array<Muscle.structMuscleList> = []
var supportingMuscleData : Array<Muscle.structMuscleList> = []
override func viewDidLoad() {
super.viewDidLoad()
if (machineId != nil) {
if (objMachine.loadById(Id: machineId!) == true) {
self.title = objMachine.name
txtName.text = objMachine.name
txtType.text = String(objMachine.typeId)
}
} else {
deleteToolbar.isHidden = true
}
lvMainMuscles.delegate = self
lvMainMuscles.dataSource = self
lvMainMuscles.allowsMultipleSelection = true
self.lvMainMuscles.register(UITableViewCell.self, forCellReuseIdentifier: "mainMuscleCell")
lvSupportingMuscles.delegate = self
lvSupportingMuscles.dataSource = self
lvSupportingMuscles.allowsMultipleSelection = true
self.lvSupportingMuscles.register(UITableViewCell.self, forCellReuseIdentifier: "supportingMuscleCell")
getData()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func btnSaveClick(_ sender: Any) {
objMachine.name = txtName.text!
objMachine.isSystem = false
objMachine.typeId = Int64(txtType.text!)!
let returnId = objMachine.save()
print("edited/saved id: \(returnId)")
let selectedrows = lvMainMuscles.indexPathsForSelectedRows
if (selectedrows?.count)! > 0 {
for row in selectedrows! {
print(row.row)
}
}
_ = self.navigationController?.popViewController(animated: true)
}
#IBAction func btnDeleteClick(_ sender: Any) {
let alert = UIAlertController(title: title, message: "Do you really want to delete the machine?", preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "Delete", style: .default, handler: { action in
if self.objMachine.delete() == true {
_ = self.navigationController?.popViewController(animated: true)
}
})
let cancelAction = UIAlertAction(title: "Cancel", style: .destructive, handler: nil)
alert.addAction(cancelAction)
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
}
func getData() {
mainMuscleData = objMuscle.getList()
supportingMuscleData = objMuscle.getList()
// searchTextField.addTarget(self, action: "textFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.lvMainMuscles {
return mainMuscleData.count
} else {
return supportingMuscleData.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell:muscleCell!
if tableView == self.lvMainMuscles {
cell = tableView.dequeueReusableCell(withIdentifier: "mainMuscleCell") as! muscleCell
cell.lblDescription.text = mainMuscleData[indexPath.row].description
}
if tableView == self.lvSupportingMuscles {
cell = tableView.dequeueReusableCell(withIdentifier: "supportingMuscleCell") as! muscleCell
cell.lblDescription.text = supportingMuscleData[indexPath.row].description
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// tableView.deselectRow(at: indexPath as IndexPath, animated: true)
if tableView == lvMainMuscles {
let cell = self.lvMainMuscles.cellForRow(at: indexPath)!
cell.accessoryType = UITableViewCellAccessoryType.checkmark;
} else {
let cell = self.lvSupportingMuscles.cellForRow(at: indexPath)!
cell.accessoryType = UITableViewCellAccessoryType.checkmark;
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if tableView == lvMainMuscles {
let cell = self.lvMainMuscles.cellForRow(at: indexPath)!
cell.accessoryType = UITableViewCellAccessoryType.none;
} else {
let cell = self.lvSupportingMuscles.cellForRow(at: indexPath)!
cell.accessoryType = UITableViewCellAccessoryType.none;
}
}
the error I get is:
Could not cast value of type 'UITableViewCell' (0x10a63c778) to
'WorkoutPartner.muscleCell' (0x107b422f0).
in this line:
cell = tableView.dequeueReusableCell(withIdentifier: "supportingMuscleCell") as! muscleCell
I don't understand why, since I am using the same cell in another view and it works.
i hope you have got an idea,
thank you very much
JYB
From your question and code what I understood is that the two tables have same design for the cells in same UIView.
In this case whenever a cell design is reused, we should make an XIB of your custom table cell, register that NIB with table and then deque in cellForRow
Here is a quick Sample I made for you.
Here is the controller code part:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var firstTable: UITableView!
#IBOutlet weak var secondTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
firstTable.dataSource = self
firstTable.delegate = self
secondTable.dataSource = self
secondTable.delegate = self
//Registering Cell with tables
self.firstTable.register(UINib(nibName: "MuscleTableCell", bundle: nil), forCellReuseIdentifier: "MuscleTableCell")
self.secondTable.register(UINib(nibName: "MuscleTableCell", bundle: nil), forCellReuseIdentifier: "MuscleTableCell")
}
}
extension ViewController : UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.firstTable {
return 5
} else {
return 2
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == self.firstTable {
let cell = tableView.dequeueReusableCell(withIdentifier: "MuscleTableCell") as! MuscleTableCell
cell.descriptionLabel.text = "Muscle Table Cell"
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "MuscleTableCell") as! MuscleTableCell
cell.descriptionLabel.text = "Supporting Table Cell"
return cell
}
}
}
The CustomCellClass
import UIKit
class MuscleTableCell: UITableViewCell {
#IBOutlet weak var descriptionLabel: 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
}
}
The Custom Cell have its nib file too.
And the Output:
You have registered UITableViewCell.self for the UITableView to use, therefore, it is returning that. Try registering your custom cell class instead.
OK if someone has the same problem:
I solved it by removing these two lines of code:
self.lvMainMuscles.register(UITableViewCell.self, forCellReuseIdentifier: "mainMuscleCell")
and
self.lvSupportingMuscles.register(UITableViewCell.self, forCellReuseIdentifier: "supportingMuscleCell")
I think my error was, that I registered the cell although I have a prototype cell in my storyboard.