3

I am trying to create a custom cell for my UITableView but I am having some difficulty.

First off I cannot use the Interface Builder, as I am experiencing a variation on this bug in Xcode. Every time I click on an element in the Interface Builder everything in that view gets a height and width of zero and gets repositioned outside of the view. Besides, I would like to learn how to do this programmatically.

Secondly I am using the Swift language for my project. I have been trying to follow this demonstration, and doing my best to convert the Objective C code over to Swift, but whenever I run into problems I end up being stuck. I presume this is because I am not converting the code over correctly.

Thirdly I found this video but despite being fairly difficult to follow (lots of the code is just copied and pasted without much explanation to what it does or why), it still ends up using the Interface Builder to change various parts.

I have a basic UITableView set up fine. I just want to be able to add a custom cell to that table view.

  • Can this be done using pure programming, or do I need to use the Interface Builder?

  • Can anyone point me in the right direction or help me out in creating a custom cell programmatically in Swift?

Many thanks.

Community
  • 1
  • 1
Jimmery
  • 9,783
  • 25
  • 83
  • 157

2 Answers2

8

In general: Everything is possible in pure programming ;-)

  1. Create a custom class for your tableView cell and there setup all the elements, properties and the visual layout. Implement the required methods init(style,reuseidentifier)

  2. In your custom class for the UITableViewController register the custom cell class using registerClass(forCellReuseIdentifier)

  3. Setup your delegate and datasource for the custom tableViewController

Finally, you create the cells in cellForRowAtIndexPath:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("myReuseIdentifier", forIndexPath: indexPath) as MyCustomTableViewCell 

    // configure the cell using its properties

    return cell
}

This should be the basic steps.

zisoft
  • 22,770
  • 10
  • 62
  • 73
  • Thanks for this answer - its been very helpful! however I am stuck with registering the custom cell class. The custom cell class insists on have this initializer `required init(coder aDecoder:NSCoder)`, and I cant seem to be able to initialize the cell without this, Xcode also kicks out an error if I just try to use `init(style: reuseIdentifier:)`. What `NSCoder` do I need to use here? – Jimmery Nov 25 '14 at 10:56
  • Hmm, I think I'm stuck on this too. May I ask why you really want to do all this by code where InterfaceBuilder makes your live much easier? – zisoft Nov 25 '14 at 11:38
  • 2
    like I said - I literally cannot use Interface Builder - every time I click on an item it gets repositioned and shrunk to a size of zero. Interface Builder isnt just making my life harder - its making me tear my hair out. Ive upgraded Xcode to the most recent version too - seems like a few others are also experiencing this bug too (see the link in my original post). – Jimmery Nov 25 '14 at 11:41
  • Maybe it helps to completely uninstall Xcode by using an AppCleaner. – zisoft Nov 25 '14 at 11:50
  • ouch - do you think this will help? – Jimmery Nov 25 '14 at 12:18
  • Its worth a try... I have no such problems with XCode. I use 6.1 and 6.2 Beta in parallel. – zisoft Nov 25 '14 at 12:43
  • Ok, so I've reinstalled Xcode. I am not totally convinced if this has fixed my problems with Interface Builder, but so far so good. Also I was registering the class wrong (I was trying to register an instance of the class instead of the class itself), now that Ive fixed this everything is working perfectly! Many thanks for your help. – Jimmery Nov 25 '14 at 17:02
  • I am the author of that video you mentioned. Here is some better (and updated) article I wrote using Swift: http://blog.idevwizard.com/how-to-create-uitableviewcell-subclasses/ – ppalancica Jun 12 '17 at 04:45
8

If you're looking for more code, here is an example of a custom cell that I created:

//  File: vDataEntryCell.swift
import UIKit

class vDataEntryCell: UITableViewCell
{

//-----------------
// MARK: PROPERTIES
//-----------------

//Locals
var textField : UITextField = UITextField()

//-----------------
// MARK: VIEW FUNCTIONS
//-----------------

///------------
//Method: Init with Style
//Purpose:
//Notes: This will NOT get called unless you call "registerClass, forCellReuseIdentifier" on your tableview
///------------
override init(style: UITableViewCellStyle, reuseIdentifier: String!)
{
    //First Call Super
    super.init(style: style, reuseIdentifier: reuseIdentifier)

    //Initialize Text Field
    self.textField = UITextField(frame: CGRect(x: 119.00, y: 9, width: 216.00, height: 31.00));

    //Add TextField to SubView
    self.addSubview(self.textField)
}


///------------
//Method: Init with Coder
//Purpose:
//Notes: This function is apparently required; gets called by default if you don't call "registerClass, forCellReuseIdentifier" on your tableview
///------------
required init(coder aDecoder: NSCoder)
{
    //Just Call Super
    super.init(coder: aDecoder)
}
}

Then in my UITableViewController class I did the following:

//  File: vcESDEnterCityState.swift
import UIKit

class vcESDEnterCityState: UITableViewController
{

//-----------------
// MARK: VC FUNCTIONS
//-----------------


///------------
//Method: View Will Appear
//Purpose:
//Notes:
///------------
override func viewWillAppear(animated: Bool)
{
    //First Call Super
    super.viewWillAppear(animated)

    //Register the Custom DataCell
    tvCityStateForm.registerClass(vDataEntryCell.classForCoder(), forCellReuseIdentifier: "cell")
}

//-----------------
// MARK: UITABLEVIEW DELEGATES
//-----------------

///------------
//Method: Cell for Row at Index Path of TableView
//Purpose:
//Notes:
///------------
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    //Get Reference to Cell
    var cell : vDataEntryCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as vDataEntryCell

    //...Do Stuff

    //Return Cell
    return cell
}

}
user2266987
  • 2,912
  • 1
  • 18
  • 5
  • 1
    what is this refer tvCityStateForm in tvCityStateForm.registerClass(vDataEntryCell.classForCoder(), forCellReuseIdentifier: "cell") }.Tableview or view? – Lydia Jun 01 '15 at 06:37