Insert custom UITableViewCell on button click - ios

I've been trying and researching for the whole day and still not able to find the right answer.
I have a button and I want to insert customized UITableViewCell in my static UITableView upon button click.
Here's what I have done. I created an xib file with my customized UITableViewCell and have assigned swift file to it.
In the viewdidload of my tableviewcontroller, I registered my UITableViewCell:
override public func viewDidLoad() {
super.viewDidLoad()
let nib = UINib(nibName: "TableViewCell", bundle: nil)
addContactTableView.registerNib(nib, forCellReuseIdentifier: "cell")
}
Here's my function for my button click:
#IBAction func buttonClick(sender: AnyObject) {
if let button = sender as? UIButton {
if let superview = button.superview {
if let cell = superview.superview as? UITableViewCell {
indexPath_g = self.tableView.indexPathForCell(cell)!
}
}
}
print(indexPath_g.row)
addContactTableView.beginUpdates()
addContactTableView.insertRowsAtIndexPaths([
NSIndexPath(forRow: indexPath_g.row, inSection: 1)
], withRowAnimation: .Automatic)
addContactTableView.endUpdates()
}
And my cellForRowAtIndexPath:
public override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath_g) as! TableViewCell
if(indexPath.section == 1) {
//Configure the cell...
cell.detail_field.placeholder = "Phone"
}
return cell
}
I tried to run this and I keep getting this error:
fatal error: unexpectedly found nil while unwrapping an Optional value

Insert the UITableviewCell in button action. When tapping on button, you can get the indexPath of the cell and insert anywhere in the UItableview.Just add two methods [tableView beginUpdate] and [tableView endUpdate] after inserting the cell using insertRowsAtIndexPaths method.

My first guess is your cellForRow method:
public override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath_g) as! TableViewCell
...
}
change indexPath_g to indexPath

Related

Why UITableViewCell needs to be registered?

these are all codes in my demo:
import UIKit
class TableViewController: UITableViewController {
var numberOfCell = 0
#IBAction func addAction() {
numberOfCell = numberOfCell + 1
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numberOfCell + 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "FirstCell", for: indexPath)
let addButton = cell.viewWithTag(99) as! UIButton
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "SecondCell", for: indexPath)
let deleteButton = cell.viewWithTag(100) as! UIButton
let textField = cell.viewWithTag(101) as! UITextField
return cell
}
} else {
return super.tableView(tableView, cellForRowAt: indexPath)
}
}
}
I set cells' identifier in Attributes inspector at storyboard file, didn't register the cells, everything goes right like this:
Tap Add button, show a new cell with a button and a textfield.
But in my project, I use the same way, when I tap Add button, the app will crash, and report this error:
*** Terminating app due to uncaught exception
'NSInternalInconsistencyException', reason: 'unable to dequeue a cell
with identifier SecondCell - must register a nib or a class for
the identifier or connect a prototype cell in a storyboard'
I have tried register cell use this code:
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "SecondCell")
But if I do this, the app will crash at let deleteButton = cell.viewWithTag(100) as! UIButton and let textField = cell.viewWithTag(101) as! UITextField because them are nil.
I think my project and demo have no differences, I don't know how to deal with this issues.
If you are using nib file then you need to register your cell in the tableview.
self.tableView.register(UINib(nibName: "nibName", bundle: nil), forCellReuseIdentifier: "CellIdentifier")

Add Custom Cell inside Custom Cell

I have an interesting problem. as i am new to Swift.
I have created on TableView and added CUSTOM CELL using Storyboard. Now i want add another CUSTOM CELL When click on first CUSTOM CELL UIButton.
Second Custom Cell is created using XIB. now when i register That second Cell in didload then i see blank tableview as Second custom cell is Blank.
i have used following Code:
for registering Second cell
self.tableView.registerNib(UINib(nibName: "customCell", bundle: nil), forCellReuseIdentifier: "customCell")
and cell for row at index
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! Cell
cell.nameLbl.text = "Hello hello Hello"
let Customcell = tableView.dequeueReusableCellWithIdentifier("customCell", forIndexPath: indexPath) as! customCell
if self.Selected == "YES" {
if self.selectedValue == indexPath.row {
return Customcell
}
return cell
}
else{
return cell
}
}
Here Cell object is for Storyboard Cell and Customcell is for XIB Second custom cell.
please suggest me how to do that.
First ensure your ViewController is the UITableViewDelegate and UITableViewDataSource of the tableView, and that you have an outlet for the tableView
Next you need to register the custom cell in the viewDidLoad method:
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: "customCell")
}
It is easiest to save an array of cells that have been selected if you are going to have more than 1 cell that you want to modify when pressed. This can be a variable within the ViewController:
var customCellIndexPaths: [IndexPath] = []
when a cell is selected you can simply add it to the array of custom cell IndexPaths (if it is not already a custom cell), and then reload that cell:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if customCellIndexPaths.contains(indexPath) == false {
customCellIndexPaths.append(indexPath)
tableView.reloadRows(at: [indexPath], with: .automatic)
}
}
In the cellForRowAt method we must check whether the cell has been selected and if so return the custom cell, else return a normal cell:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if customCellIndexPaths.contains(indexPath) {
return tableView.dequeueReusableCell(withIdentifier: "customCell")!
}
let cell = UITableViewCell(style: .default, reuseIdentifier: "normalCell")
cell.textLabel?.text = "Regular Cell"
return cell
}
There you have it. Now you should receive a smooth animation of a normal cell becoming a CustomCell when being selected.

TableViewCell not updating properly swift 2.2

In my app I created two custom tableview cells.
Problem I am facing now the second tableview cell update with last element of the array only.
In cellForRowAtIndexpath array elements are displaying fine.
Consider [ "Value1", "Value2" ] is my array. In tableView only value2 is displaying in two cells.
var title = ["value1","value2"]
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let row = indexPath.row
let x = Id[indexPath.row]
if x == 0{
let cell1 = tableView.dequeueReusableCellWithIdentifier("Cell1", forIndexPath: indexPath) as! MyCell1
return cell1
}
else{
let cell2 = tableView.dequeueReusableCellWithIdentifier("Cell2", forIndexPath: indexPath) as! MyCell2
for index in 0..<myArray.count{
cell2.titleButton.setTitle(title[index],forState:UIControlState.Normal)
}
return cell2
}
}
I am stuck here, your help will be appreciated.
Following is the solution, reason it was going out of range was because value incremented when cell were dequed as cellforrowAtIndexPath was called every time we scrolled down(since some cells were not visible and these cells were dequed when we scrolled down):-
var name = ["HouseBolo","HouseBolo1","HouseBolo2","HouseBolo3"]
var propertyVal:Int = 0
var projectVal:Int = 0
var type = ["Apartment","Villa","Home","Flat","Plot"]
var arrangedData = [String]()
var flatId = [0,1,2,0,0]
override func viewDidLoad() {
super.viewDidLoad()
// I want the Expected Output in Tableview Cell is
// 1. Apartment 2. HouseBolo 3. HouseBolo1 4. Villa 5. Home
for item in flatId {
if item == 0 {
arrangedData.append(type[propertyVal])
propertyVal+=1
}
else {
arrangedData.append(name[projectVal])
projectVal+=1
}
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrangedData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let flatDetails = flatId[indexPath.row]
// For Property Cell
if flatDetails == 0{
let cell = tableView.dequeueReusableCellWithIdentifier("Cell1", forIndexPath: indexPath) as? PropertyCell
if(cell != nil) {
cell!.pType.text = arrangedData[indexPath.row]
}
return cell!
}
// For Project Cell
else {
let cellan = tableView.dequeueReusableCellWithIdentifier("Cell2", forIndexPath: indexPath) as? ProjectCell
if(cellan != nil) {
cellan!.projectName.setTitle(arrangedData[indexPath.row], forState: UIControlState.Normal)
}
return cellan!
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
You need to use :
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! searchCell
in :
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {}
block.
searchCell : is a class of type : UITableViewCell
After that, go in Storyboard and change the identifier of your cell with : "cell"
In the code...
let cell2 = tableView.dequeueReusableCellWithIdentifier("Cell2", forIndexPath: indexPath) as! MyCell2
for index in 0..<myArray.count{
cell2.titleButton.setTitle(title[index],forState:UIControlState.Normal)
}
return cell2
you are iterating over 'myArray' and assigning the value to 'cell2.titleButton'. Cell 2 will always have the last value assigned to it's title. It's assigning it to 'value1', then reassigning it to 'value2'. Looping through the array seems to be the issue (assuming the cells are displaying - just always showing the title from the last item in the array.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
}
You have to add your custom tableview cell class name in the place of UITableViewCell
Something like this -
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> **custom tableview cell class name**
{
}
And also in Storyboard ,change the identifier of your cell with : "cell1" and "cell2"

Setting up a Custom Cell in a Tableview with SWIFT

I'm trying to create a custom cell that will only be applied to one single CELL in a Section.
So a create a custom cass called buttonsTableViewCell, that is pretty much empty and only have one label called weightLabel() code bellow:
class buttonsTableViewCell: UITableViewCell {
#IBOutlet weak var weightLabel: 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
}
}
On the Main.storyboard i connected everything:
Now this is what i'm trying to do in the viewcontroller class, that controls the Tableview that has the cell.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = "Testing"
if indexPath.row == 1 { // So it only changes this cell
cell = tableView.dequeueReusableCellWithIdentifier("buttonsCell", forIndexPath: indexPath) as buttonsTableViewCell
cell.weightLabel?.text = "Weight" // ERROR UITableViewCell does not have a member named 'weightLabel'
}
return cell
}
What i'm doing wrong? Thanks in advance for the help.
Swift is statically typed language with type inference. So when you first assign the value of cell outside your if condition, the type of the cell variable is set to a normal UITableViewCell. Just use a different variable name like
if indexPath.row == 1 {
var buttonCell = tableView.dequeueReusableCellWithIdentifier("buttonsCell", forIndexPath: indexPath) as buttonsTableViewCell
buttonCell.weightLabel?.text = "Weight"
return buttonCell
}
var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = "Testing"
return cell

UITableView in Swift

I'm struggling to figure out what's wrong with this code snippet. This is currently working in Objective-C, but in Swift this just crashes on the first line of the method. It shows an error message in console log: Bad_Instruction.
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell
if (cell == nil) {
cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "Cell")
}
cell.textLabel.text = "TEXT"
cell.detailTextLabel.text = "DETAIL TEXT"
return cell
}
Also see matt's answer which contains the second half of the solution
Let's find a solution without creating custom subclasses or nibs
The real problem is in the fact that Swift distinguishes between objects that can be empty (nil) and objects that can't be empty. If you don't register a nib for your identifier, then dequeueReusableCellWithIdentifier can return nil.
That means we have to declare the variable as optional:
var cell : UITableViewCell?
and we have to cast using as? not as
//variable type is inferred
var cell = tableView.dequeueReusableCellWithIdentifier("CELL") as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "CELL")
}
// we know that cell is not empty now so we use ! to force unwrapping but you could also define cell as
// let cell = (tableView.dequeue... as? UITableViewCell) ?? UITableViewCell(style: ...)
cell!.textLabel.text = "Baking Soda"
cell!.detailTextLabel.text = "1/2 cup"
cell!.textLabel.text = "Hello World"
return cell
Sulthan's answer is clever, but the real solution is: don't call dequeueReusableCellWithIdentifier. That was your mistake at the outset.
This method is completely outmoded, and I'm surprised it has not been formally deprecated; no system that can accommodate Swift (iOS 7 or iOS 8) needs it for any purpose whatever.
Instead, call the modern method, dequeueReusableCellWithIdentifier:forIndexPath:. This has the advantage that no optionals are involved; you are guaranteed that a cell will be returned. All the question marks and exclamation marks fall away, you can use let instead of var because the cell's existence is guaranteed, and you're living in a convenient, modern world.
You must, if you're not using a storyboard, register the table for this identifier beforehand, registering either a class or a nib. The conventional place to do that is viewDidLoad, which is as early as the table view exists at all.
Here's an example using a custom cell class:
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(MyCell.self, forCellReuseIdentifier: "Cell")
}
// ...
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath:indexPath) as MyCell
// no "if" - the cell is guaranteed to exist
// ... do stuff to the cell here ...
cell.textLabel.text = // ... whatever
// ...
return cell
}
But if you're using a storyboard (which most people do), you don't even need to register the table view in viewDidLoad! Just enter the cell identifier in the storyboard and you're good to go with dequeueReusableCellWithIdentifier:forIndexPath:.
#Sulthan's answer is spot on. One possible convenience modification would be to cast the cell as a UITableViewCell!, rather than a UITableViewCell.
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell = tableView.dequeueReusableCellWithIdentifier("CELL") as UITableViewCell!
if !cell {
cell = UITableViewCell(style:.Default, reuseIdentifier: "CELL")
}
// setup cell without force unwrapping it
cell.textLabel.text = "Swift"
return cell
}
Now, you can modify the cell variable without force unwrapping it each time. Use caution when using implicitly unwrapped optionals. You must be certain that the value you are accessing has a value.
For more information, refer to the "Implicitly Unwrapped Optionals" section of The Swift Programming Language.
Try this:
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel.text = "\(indexPath.row)"
return cell
}
Note that you should register you UITableViewCell and ID when creating instantiating your UITableView:
tableView.delegate = self
tableView.dataSource = self
tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: "Cell")
Here is what I wrote to get it working...
First Register the table view cell with the table view
self.tableView.registerClass(MyTableViewCell.self, forCellReuseIdentifier: "Cell")
Then configure cellForRowAtIndexPath
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as MyTableViewCell
cell.textLabel.text = "Cell Text"
cell.detailTextLabel.text = "Cell Detail Text in Value 1 Style"
return cell
}
I then defined a custom cell subclass write at the bottom of the file (since its so much easier now)
class MyTableViewCell : UITableViewCell {
init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: UITableViewCellStyle.Value1, reuseIdentifier: reuseIdentifier)
}
}
Here is a simple way to define table cell in swift 2:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let identifier = "cell"
let cell = tableView.dequeueReusableCellWithIdentifier(identifier) ??
UITableViewCell.init(style: UITableViewCellStyle.Default, reuseIdentifier: identifier)
cell.textLabel!.text = "my text"
return cell
}
Swift 3:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "cell"
let cell = tableView.dequeueReusableCell(withIdentifier: identifier) ??
UITableViewCell(style: .default, reuseIdentifier: identifier)
cell.textLabel!.text = "my text"
return cell
}
There's a few answers here, but I don't think any of them are ideal, because after the declaration you're ending up with an optional UITableViewCell, which then needs a cell!... in any declarations. I think this is a better approach (I can confirm this compiles on Xcode 6.1):
var cell:UITableViewCell
if let c = tableView.dequeueReusableCellWithIdentifier("cell") as? UITableViewCell {
cell = c
}
else {
cell = UITableViewCell()
}
Well, I have done this way:
Steps for UITableView using Swift:
Take UITableView in ViewController
Give Referencing Outlets in ViewController.swift class
Give Outlets dataSource & delegate to ViewController
Now Swift code in ViewController.swift class:
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var mTableView: UITableView!
var items: [String] = ["Item 1","Item 2","Item 3", "Item 4", "Item 5"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.mTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = self.mTableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
cell.textLabel?.text = self.items[indexPath.row]
println(self.items[indexPath.row])
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
println("You have selected cell #\(indexPath.row)!")
}
}
Now it's time to Run your program.
Done
Actually in the Apple's TableView Guide document and Sample Code you will find the sentence below:
If the dequeueReusableCellWithIdentifier: method asks for a cell that’s defined in a storyboard, the method always returns a valid cell. If there is not a recycled cell waiting to be reused, the method creates a new one using the information in the storyboard itself. This eliminates the need to check the return value for nil and create a cell manually.
So,we could just code like this:
var identifer: String = "myCell"
var cell = tableView.dequeueReusableCellWithIdentifier(identifer) as UITableViewCell
cell.textLabel.text = a[indexPath.row].name
cell.detailTextLabel.text = "detail"
I think this is a suitable way to use tableView
Using "as" keyword would do the following two steps:
1.creating a optional value which wrap a variable of UITableViewCell;
2.unwrapping the optional value.
So,by doing this
var cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("Component") as UITableViewCell
you would get a "plain" UITableViewCell type variable: cell.Theoretically speaking, it's ok to do this.But the next line
if (cell == nil) {}
makes trouble, because in swift, only the optional value can be assigned with nil.
So, to solve this problem, you have to make cell a variable of Optional type. just like this:
var cell = tableView.dequeueReusableCellWithIdentifier("Component") as? UITableViewCell
using the keyword "as?" would create a Optional variable, and this, undoubtedly, can be assigned with nil.
For cell template:
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let myCell : youCell = youCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")
return myCell
}
bro, please take a look at the sample https://github.com/brotchie/SwiftTableView
Why not this?
(please delete if i am not in the goal...)
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
if let cell: UITableViewCell = theTableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as? UITableViewCell {
// cell ok
}else{
// not ok
}
}
I have done in following way: to show detailTextLabel. text value
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let CellIdentifier: String = "cell"
var cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier) as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: CellIdentifier)
}
//cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
// parse the value of records
let dataRecord = self.paymentData[indexPath.row] as! NSDictionary
let receiverName = dataRecord["receiver_name"] as! String
let profession = dataRecord["profession"] as! String
let dateCreated = dataRecord["date_created"] as! String
let payAmount = dataRecord["pay_amount"] as! String
println("payment \(payAmount)")
cell!.textLabel?.text = "\(receiverName)\n\(profession)\n\(dateCreated)"
cell!.detailTextLabel?.text = "$\(payAmount)"
cell!.textLabel?.numberOfLines = 4
return cell!
}// end tableview
UITableView Demo using Playground
//: Playground - noun: a place where people can play
import UIKit
import PlaygroundSupport
class TableviewDemoDelegate:NSObject,UITableViewDataSource,UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 100
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell:UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath)
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
}
cell?.textLabel?.text = "Item \(indexPath.row+1)"
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You have selected cell #\(indexPath.row)!")
}
}
var tableView = UITableView(frame:CGRect(x: 0, y: 0, width: 320, height: 568), style: .plain)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
let delegate = TableviewDemoDelegate()
tableView.delegate = delegate
tableView.dataSource = delegate
PlaygroundPage.current.liveView = tableView
I went through your codes and most probably the reason for the crash is you are trying to typecast an optional value which is not assigned
Now consider the line of code below
var cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell
When there are no cells in the tableview you are still trying to typecast as UITableView.When the compiler tries to typecast nil value you face this issue
The correct statement should be
var cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell")
You can use if else statement to typecast for values which holds
Try this code
var cell:CustomTableViewCell = tableView.dequeueReusableCellWithIdentifier("CustomTableViewCell") as CustomTableViewCell
cell.cellTitle.text="vijay"
https://github.com/iappvk/TableView-Swift

Resources