How to load Custom cell (Xib) in UITableview using Swift - ios

Here's my code
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return 10
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell :UITableViewCell = tableView.dequeueReusableCellWithIdentifier("discovered") as UITableViewCell!
bluetoothlog.registerNib(UINib(nibName: "devicedet", bundle: nil), forCellReuseIdentifier: "discovered")
//NSBundle.mainBundle().loadNibNamed("devicedet", owner: nil, options: nil)[0] as UITableViewCell
cell = blucell
devname.text = peri[indexPath.row]
devstrength.text = signalstrength[indexPath.row]
bluetoothlog.backgroundColor = UIColor.clearColor()
return cell
}
I have tried with the above code and nothing is displayed in Tableview, please help me to change this code working
Thanks

Register your NIB with the reuse identifier:
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerNib(UINib(nibName: "devicedet", bundle: nil), forCellReuseIdentifier: "Cell")
}
Your cellForRowAtIndexPath would then instantiate the cell.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! devicedet
return cell
}

the command registerNib should be called in ViewDidLoad, but not in each call of cell for row
what is 'bluecell'? In your call-back cellforTable.., you assign cell = blucell -> this can cause your problems.
Try this:
import UIKit
class YourViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
//call register nib here!!
bluetoothlog.registerNib(UINib(nibName: "devicedet", bundle: nil), forCellReuseIdentifier: "discovered")
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return peri.count
}
//it seem that you have to add a è
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell!
{
let cell :UITableViewCell = tableView.dequeueReusableCellWithIdentifier("discovered") as UITableViewCell!
/* REMOVE THIS
bluetoothlog.registerNib(UINib(nibName: "devicedet", bundle: nil), forCellReuseIdentifier: "discovered")
//NSBundle.mainBundle().loadNibNamed("devicedet", owner: nil, options: nil)[0] as UITableViewCell
*/
//// THEN, UPDATE YOUR CELL with YOUR DATAs
/* I don't understand what are you doing with this line of code:
cell = blucell
*/
devname.text = peri[indexPath.row]
devstrength.text = signalstrength[indexPath.row]
//Seem that bluetoothlog is the tableview, you should call it in viewdidload or viewwillappear()
bluetoothlog.backgroundColor = UIColor.clearColor()
return cell
}
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell :devicedet = tableView.dequeueReusableCellWithIdentifier("discovered") as UITableViewCell!
bluetoothlog.registerNib(UINib(nibName: "devicedet", bundle: nil), forCellReuseIdentifier: "discovered")
//NSBundle.mainBundle().loadNibNamed("devicedet", owner: nil, options: nil)[0] as UITableViewCell
cell = blucell
devname.text = peri[indexPath.row]
devstrength.text = signalstrength[indexPath.row]
bluetoothlog.backgroundColor = UIColor.clearColor()
return cell
}

In viewDidLoad register XIB as shown below
var userDetailsNIB = UINib(nibName: "UserDetailsCell", bundle: nil)
viewListingTable.registerNib(userDetailsNIB, forCellReuseIdentifier: "UserDetailsViewCellID")
And in func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
function use it by access it with Identifier which created in viewDidLoad method
let cell = tableView.dequeueReusableCellWithIdentifier("UserDetailsViewCellID") as UserDetailsViewCell
return cell

if you would like to Load custom cell(Xib) in UITableView in swift ,you may use the following code.
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return array.count; //This function returns number of rows in table view
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:YourTableViewCell! = tableView.dequeueReusableCellWithIdentifier("YourTableViewCell", forIndexPath:indexPath)as! YourTableViewCell
// Do additional code here
}
Don’t forget to register nib in viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
// registering your nib
let yourNibName = UINib(nibName: "YourTableViewCell", bundle: nil)
tableView.registerNib(yourNibName, forCellReuseIdentifier: "YourTableViewCell")
// Do any additional setup after loading the view.
}

Register xib Cell in Swift
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: "XibCell", bundle: nil), forCellReuseIdentifier: "Cell")
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! UITableViewCell
return cell
}

My code:
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(
UINib(nibName: "XibCell", bundle: nil),
forCellReuseIdentifier: "Cell"
)
}
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
return cell as! UITableViewCell
}

import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
//MARK:- Sample Data Array to load in TableView
let sampleArrray: \[String\] = \["val1", "val2", "val3", "val4", "val5"]
//MARK:- Cell reuse identifier
let cellReuseIdentifier = "cell"
//MARK:- UITableView outlet
#IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Registering the custom cell
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
// Setting delegate and Datasourse as same viewcontroller (this code is not neccessory if we are setting it from storyboard)
tableView.delegate = self
tableView.dataSource = self
}
//UITableview required methods
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sampleArrray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as UITableViewCell!
cell.textLabel?.text = sampleArrray\[indexPath.row\]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("clicked at: \(indexPath.row)")
//Here u can get the selected cell and add action related to this cell seelction
}
Added Screenshot for setting Datasource and delegate from storyboard

Your fuction registerNib , you try to write in viewDidLoad() method and remove from cellForRowAtIndexPah and then test your project
Your Cell Instance should be of CustomCell instance and not of UITableView Cell.
var cell :UITableViewCell should be replaced by
var cell :devicedet

Related

UITableViewCell gets deleted after scrolling

I am trying to create a ToDo list application. For this application, I require a custom UITableViewCell. I am trying to use my custom cell, however, when I run the app and try to scroll through the table view all the cells get deleted.
This is my code:
class ToDoListVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let nib = UINib(nibName: "TodoCell", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "customCell")
tableView.delegate = self
tableView.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return HomeVC.ToDoEvents.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "customCell") as! TodoCell
let eventName = HomeVC.ToDoEvents[indexPath.row].name
let eventTime = HomeVC.ToDoEvents[indexPath.row].time
let completion = HomeVC.ToDoEvents[indexPath.row].isComplete
cell.initialize(task: eventName!, length: eventTime!, completion: completion!)
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 70
}
}
I am not sure what I am doing wrong. I went through some of the other threads, however, none of them solved my problem.

Create tableView by storyboard use custom tableViewCell form xib get Assertion failure

Create tableView by storyboard, and in the tableView delegate method:tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell occurs a exception:
*** Assertion failure in -[UITableView dequeueReusableCellWithIdentifier:forIndexPath:],
/BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3599.6/UITableView.m:6593
my code is below:
ViewController11
#IBOutlet weak var tableView: UITableView! // tableView
// tableview delegate
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell_id: String = "cell_id"
// this line below occurs exception: Thread 1:breakpoint 5.2
var cell: TableViewCell2 = tableView.dequeueReusableCell(withIdentifier: cell_id, for: indexPath) as! TableViewCell2
if cell == nil {
//
}
var title = dataSource[indexPath.row]
cell.titlelabel?.text = String(title)
return cell
}
and my storyboard for ViewController11:
and my xib for TableViewCell2:
You have to register your UITableViewCell from the xib before you can use it:
Swift 2:
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerNib(UINib(nibName: "TableViewCell2", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "cell_id")
}
Swift 3:
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(UINib(nibName: "TableViewCell2", bundle: Bundle.main), forCellReuseIdentifier: "cell_id")
}

Separators in custom UITableView are not shown

I've created UITableView programmatically, but it doesn't show any separators. When I run the project I can see on Debug View Hierarchy that it exists, but i cannot understand why i cannot see it on simulator? Any of you knows what I'm missing or what is wrong with my code?
I'll really appreciate your help.
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
//🔵 Proerties
var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView = UITableView(frame: view.bounds)
tableView.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
tableView.dataSource = self
tableView.delegate = self
tableView.rowHeight = 100
tableView.separatorColor = UIColor.redColor()
tableView.separatorStyle = .SingleLine
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
view.addSubview(tableView)
}
// 🔵 UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
let row = indexPath.row
cell.textLabel?.text = String(row)
return cell
}
// 🔵 UITableViewDelegate
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
cell.backgroundColor = UIColor.cyanColor()
}
}

I am unable to load the table view cell inside the table view

import UIKit
class NewOrdersViewControllers: UIViewController,UITableViewDelegate,UITableViewDataSource {
var items = ["Chilli and Lemon"]
#IBOutlet var tableView:UITableView!
#IBOutlet weak var lblRestaurantNames: UILabel!
#IBOutlet weak var mapView: UIButton!
var cellIdentifier = "cell"
init() {
super.init(nibName : "NewOrdersViewControllers", bundle:nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
let nib = UINib(nibName: "tableCell", bundle: nil)
self.tableView.registerNib(nib, forCellReuseIdentifier: cellIdentifier)
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier)
tableView.delegate = self
tableView.dataSource = self
// Do any additional setup after loading the view.
}
#IBAction func mapPush(sender: AnyObject) {
let mapVC = MapViewController()
self.navigationController?.pushViewController(mapVC, animated: true)
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:tableCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! tableCell
//cell.textLabel?.text = self.items[indexPath.row] as! String
cell.RestaurantLbl.text = self.items[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
print("You selected cell #\(indexPath.row)!")
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 100
}
I have done it using xib and it shows the following error.
Could not cast value of type 'UITableViewCell' (0x1fe82bc)
In your viewDidLoad() method you register 2 different cell types for the same reuseIdentifier, so the last one (UITableViewCell) takes effect. That's why in tableView:cellForRowAtIndexPath: the cells being dequeued are also of UITableViewCell class and may not be cast to your custom cell class.
Try to remove the line:
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier)
it should fix your problem and let the tableView dequeue the correct cells.

How to load a custom table view cell in cell for row at indexpath delegate in swift

import UIKit
class NewOrdersViewControllers: UIViewController,UITableViewDelegate,UITableViewDataSource {
var items = []
#IBOutlet var tableView:UITableView!
#IBOutlet weak var lblRestaurantNames: UILabel!
#IBOutlet weak var mapView: UIButton!
var cellIdentifier = "cell"
override func viewDidLoad() {
super.viewDidLoad()
//self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
let nib = UINib(nibName: "vwTblCell", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "cell")
tableView.delegate = self
tableView.dataSource = self
// Do any additional setup after loading the view.
}
#IBAction func mapPush(sender: AnyObject) {
let mapVC = MapViewController()
self.navigationController?.pushViewController(mapVC, animated: true)
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// let cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier(cellIdentifier)! as! UITableViewCell
//
// cell.textLabel?.text = self.items[indexPath.row] as! String
//
// cell.RestaurantLbl.text = self.items[indexPath.row]
//
// cell.lblrest.text = items[indexPath.row] as! String
var cell:TblCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! TblCell
cell.lblRestaurantName.text = items[indexPath.row] as! String
return cell
}
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
print("You selected cell #\(indexPath.row)!")
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 100
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let identifier = "Custom"
var cell: CustomCell! = tableView.dequeueReusableCellWithIdentifier(identifier) as? CustomCel
if cell == nil {
tableView.registerNib(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: identifier)
cell =tableView.dequeueReusableCellWithIdentifier(identifier) as? CustomCell
}
return cell
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell:TblCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TblCell
cell.lblRestaurantName.text = items[indexPath.row] as! String
return cell;
}

Resources