I have a TableView with a custom cell that requires rather lengthy configuration and is used more than once in my app. I would like to avoid duplicated code and just configure the cell in one place. Can I create a function like this?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "betterPostCell", for: indexPath) as! BetterPostCell
return configureCell(cell)
}
Ideally, I would be able to put configureCell in my BetterPostCell class. Is this possible?
Yes, you can do it, and it's a nice way to keep your table view code from blowing up, especially if you have many different types of cells in one table view.
In your BetterPostCell class, create a method called configure like so:
func configure() {
//configure your cell
}
Then in your cellForRowAt method, just call that method from your cell:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "betterPostCell", for: indexPath) as! BetterPostCell
cell.configure()
return cell
}
You can create a protocol with a configure function and associated type Cell. Using protocol extensions, you can add default implementations for different cell types, and additional methods.
protocol CellConfigurable {
associatedType Cell
func configure(_ cell: Cell)
}
extension CellConfigurable where Cell == SomeTableViewCell {
func configure(_ cell: SomeTableViewCell) {
...
}
}
try this code to create CustomCell:-
class CustomCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.initViews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.perform(#selector(self.initViews), with: self, afterDelay: 0)
}
//MARK: Init views
func initViews() {
//Add your code
}
//MARK: Layout subviews
override func layoutSubviews() {
super.layoutSubviews()
// Here you can code for layout subviews
}
//MARK: Update all valuesw model
func updateWithModel(_ model: AnyObject) {
//here you can update values for cell
}
}
//Call CustomCell in Tableview class
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! CustomCell
cell.updateWithModel(items[indexPath.row])
return cell
}
Alright, I am trying to add content to my custom tableview cell programmatically as demonstrated in mob last question here - Swift: tableview cell content is added again and again with each reload? initializing all the content in func tableView() results in overlapping.
I have followed this question verbatim Swift. Proper initialization of UITableViewCell hierarchy And in my custom cell class (which I give a name to in my storyboard) I have:
class EventTableCellTableViewCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier) // the common code is executed in this super call
// code unique to CellOne goes here
print("INIT")
self.contentView.backgroundColor = UIColor.blackColor()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
And this init is not called because nothing is printed. The errors come in my func tableView() in my main VC. I originally had:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("eventCell", forIndexPath: indexPath) as! EventTableCellTableViewCell
// cell.eventTitle.text = names[indexPath.row]
// cell.eventDescription.text = descriptions[indexPath.row]
cell.contentView.clipsToBounds = false
//cell UIX
let eventTitleLabel = UILabel()
let dateLabel = UILabel()
let authorLabel = UILabel()
let locationLabel = UILabel()
let categoryView = UIImageView()
//then I add everything
But this didn't work so I looked at other posts and now have:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//var cell = tableView.dequeueReusableCellWithIdentifier("eventCell", forIndexPath: indexPath) as! EventTableCellTableViewCell
var cell = tableView.dequeueReusableCellWithIdentifier("eventCell", forIndexPath: indexPath) as! UITableViewCell
if (cell == nil) {
cell = EventTableCellTableViewCell.init(style: .Default, reuseIdentifier: "eventCell")
}
I have also tried doing it without the indexPath. Right now I get an error that cell cannot == nil, and not matter what I write init is not called.
How can I configure my cell programmatically?
If the cell is designed in the storyboard only init?(coder aDecoder: NSCoder) is called, init(style: style, reuseIdentifier: is never called.
And you have to set the class of the cell in Interface Builder to EventTableCellTableViewCell.
I've created UITableView and UITableViewCell programmatically. In my ViewController - viewDidLoad I do:
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.registerClass(newsCell.self, forCellReuseIdentifier: "newsCell")
later use it as:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("newsCell", forIndexPath: indexPath) as! newsCell
return cell
}
My newsCell class(shortly):
class newsCell: UITableViewCell {
let scoreLabel = UILabel()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
print("init")
self.addSubview(self.scoreLabel)
}
}
but I do not even get init on logs, so it does not call my custom cell at all. What is a problem?
Try this code below:
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: restorationIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
and forced unwrapping is dangerous. You should do it like this:
if let cell = self.tableView.dequeueReusableCellWithIdentifier("newsCell", forIndexPath: indexPath) as? newsCell{}
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
My TapCell1.swift
This is Custom UITableViewCell View
import UIKit
class TapCell1: UITableViewCell
{
#IBOutlet var labelText : UILabel
init(style: UITableViewCellStyle, reuseIdentifier: String!)
{
println("Ente")
super.init(style: UITableViewCellStyle.Value1, reuseIdentifier: reuseIdentifier)
}
override func setSelected(selected: Bool, animated: Bool)
{
super.setSelected(selected, animated: animated)
}
}
My ViewController.swift
Its All DataSource and Delegates are set correctly.But My custom Cell is not displaying.
import UIKit
class NextViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
{
#IBOutlet var label: UILabel
#IBOutlet var tableView : UITableView
var getvalue = NSString()
override func viewDidLoad()
{
super.viewDidLoad()
label.text="HELLO GOLD"
println("hello : \(getvalue)")
self.tableView.registerClass(TapCell1.self, forCellReuseIdentifier: "Cell")
}
func tableView(tableView:UITableView!, numberOfRowsInSection section:Int)->Int
{
return 5
}
func numberOfSectionsInTableView(tableView:UITableView!)->Int
{
return 1
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{
var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as TapCell1
cell.labelText.text="Cell Text"
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The Problem is My custom cell is Not displayed. Please suggest anything i did wrong.
Note: here is My code My File Download Link
I finally did it.
For TapCell1.swift
import UIKit
class TapCell1: UITableViewCell {
#IBOutlet var labelTitle: UILabel
init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: UITableViewCellStyle.Value1, reuseIdentifier: reuseIdentifier)
}
}
For NextViewController.swift
import UIKit
class NextViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var tableView: UITableView
var ListArray=NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
let nibName = UINib(nibName: "TapCell1", bundle:nil)
self.tableView.registerNib(nibName, forCellReuseIdentifier: "Cell")
for i in 0...70 {
ListArray .addObject("Content: \(i)")
}
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int)->Int {
return ListArray.count
}
func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 51
}
func numberOfSectionsInTableView(tableView: UITableView!) -> Int {
return 1
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as TapCell1
//cell.titleLabel.text = "\(ListArray.objectAtIndex(indexPath.item))"
cell.labelTitle.text = "\(ListArray.objectAtIndex(indexPath.row))"
return cell
}
}
My working code link: CUSTOMISED TABLE
You should register the class for the cell. For that do
change this line of code to
self.tableView.registerClass(TapCell1.classForCoder(), forCellReuseIdentifier: "Cell")
Edit
You code is looks fine i checked it
//cell.labelText.text="Cell Text"
cell.textLabel.text="Cell Text" // use like this
The solution is most likely pinpointed to setting the cell height manually as such:
override func tableView(tableView:UITableView!, heightForRowAtIndexPath indexPath:NSIndexPath)->CGFloat
{
return 44
}
I believe it's an Xcode beta 6 bug.
I have now been able to get Custom UITableViewCell to work.
Works on
Runs on Xcode 6 beta 6
Runs on Xcode 6 beta 5
iOS is 7.1
How
I have created a ".xib" file for the cell.
I copy it into the storyboard.
Via the storyboard I give it a Identifier.
I make sure it is a sub child of a tableview
Doing it this way, you do not need to register a class / nib etc.
This is my custom cell.
import UIKit
class TestCell: UITableViewCell {
#IBOutlet var titleImageView: UIImageView!
#IBOutlet var titleLabel: UILabel!
override init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
In your view, or where ever you extend "UITableViewDataSource".
Make sure "cell2" is the same as the "Identifier" that you gave it via the storyboard.
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell:TestCell = tableView.dequeueReusableCellWithIdentifier("cell2", forIndexPath: indexPath) as TestCell
// Example of using the custom elements.
cell.titleLabel.text = self.items[indexPath.row]
var topImage = UIImage(named: "fv.png")
cell.titleImageView.image = topImage
return cell
}
uitableviewcell
Check your Story board select the cell and look at the "identity inspector in that select CLASS type your CustomClass and MODULE type your project name
I have done this It works perfectly try this tip to avoid error to see below image and code
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
// let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
// cell.textLabel.text = array[indexPath!.row] as String
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as CustomTableViewCell
cell.nameLabel.text = array[indexPath!.row] as String
cell.RestaurentView.image = UIImage(named:images[indexPath!.row])
return cell
}
Try this following code
var cell:CustomTableViewCell = tableView.dequeueReusableCellWithIdentifier("CustomTableViewCell") as CustomTableViewCell
https://github.com/iappvk/TableView-Swift
If you are not using Storyboard then create a new file as subclass of UITableViewCell check the checkbox "also create xib files" after that set your custom cell .and here is the code for tableview
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var customcell:CustomTableViewCellClass? = tableView.dequeueReusableCellWithIdentifier("cell") as? CustomTableViewCellClass
if (customcell==nil)
{
var nib:NSArray=NSBundle.mainBundle().loadNibNamed("CustomTableViewCellClass", owner: self, options: nil)
customcell = nib.objectAtIndex(0) as? CustomTableViewCell
}
return customcell!
}
Try this following code:
var cell = tableView.dequeueReusableCell(withIdentifier: "CustomCellTableView") as? CustomCellTableView
Extention of NSOject
extension NSObject {
var name: String {
return String(describing: type(of: self))
}
class var name: String {
return String(describing: self)
}
}
Properties on Custom TableViewCell
class var nib: UINib {
return UINib(nibName:YourTableViewCell.name, bundle: nil)
}
class var idetifier: String {
return YourTableViewCell.name
}
Add in UIViewController
self.tableView.registerNib(YourTableViewCell.nib, forCellReuseIdentifier: YourTableViewCell.idetifier)
let cell = tableView.dequeueReusableCellWithIdentifier(YourTableViewCell.idetifier, forIndexPath: indexPath) as! YourTableViewCell
It is Purely swift notation an working for me
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cellIdentifier:String = "CustomFields"
var cell:CustomCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? CustomCell
if (cell == nil)
{
var nib:Array = NSBundle.mainBundle().loadNibNamed("CustomCell", owner: self, options: nil) cell = nib[0] as? CustomCell
}
return cell!
}