Pass data to UITableViewCell when initialising - ios

I have a variable that I need to pass from the main UITableView to the cell subview to use in the initialisation method. I tried doing this:
class CollectionCell : UITableViewCell {
var collectionElement : PFObject = PFObject(className:"CollectionElement")
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.collectionElementArray = (collectionElement["elementFileArray"] as? [PFObject])!
...
}
I then create the cell in this way:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
...
let cell : CollectionCell = tableView.dequeueReusableCellWithIdentifier("CollectionCell", forIndexPath: indexPath) as! CollectionCell
cell.collectionElement = collectionElements[indexPath.row]
return cell
}
The variable is not set in the init method.

As ncerezo says the cells are not getting created, they are getting recycled so no init functions get called. the better approach is to use didSet on your collectionElement variable and do whatever view updating based on the new value there after ensuring it isn't nil. Then when you set the property of the cell in tableView(tableView: , cellForRowAtIndexPath:) the cell will actually update itself.
var collectionElement : PFObject = PFObject(className:"CollectionElement") {
didSet {
// Update the cell's view elements here, rather than an init function
}
}

UITableView reuses cells, and it's responsible for creating them.
You are NOT creating the cell: as the method explains by its name, dequeueReusableCellWithIdentifier just gets an already created (and probably used) cell from the table view.
Imagine that, given your cell size and device screen, the tableView can show 10 rows at a time. It will create a few more, lets say 12, and then will call cellForRowAtIndexPath on the UITableViewDataSource every time it needs to fill a cell with new information to make it visible.
When you call dequeueReusableCellWithIdentifier, you get one of those already created cells, and you're responsible for updating the necessary elements on it to reflect the underlying data. You can thus not assume that any part of it will be "empty" or uninitialized.

Related

What does Apple mean by term "registers" in regards to creating new tableView cells?

I'm working through an exercise which uses tableviews. I noticed within a test during the exercise, they use a method I haven't needed in the past when implementing tableviews from storyboards. The method is:
func register(AnyClass?, forCellReuseIdentifier: String)
After reading the short description of this function in the reference pages. I'm curious to know what does apple mean by term "registers"? I half assume that since we are doing this exercise programmatically at the moment, this function is only needed if you're creating UITableviews programmatically. If this statement is incorrect, please let me know as I'd like to learn more.
Here is the code from the example:
func test_CellForRow_DequesCellFromTableView(){
let mockTableView = MockTableView()
mockTableView.dataSource = sut
mockTableView.delegate = sut
mockTableView.register(ItemCell.self, forCellReuseIdentifier: "ItemCell")
sut?.itemManger?.add(ToDoItem.init(title: "Foo"))
mockTableView.reloadData()
_ = mockTableView.cellForRow(at: IndexPath.init(row: 0, section: 0))
XCTAssertTrue(mockTableView.cellGotDequeed)
}
The DequeueReusable methods are there to check if any reusable cells are left before creating new ones. Hope you have an idea about the working of reusable cells
What happens when the queue is empty? Now we do need to create a cell. We can follow 2 methods to create a cell,
Create cell manually
Create it automatically by registering cell with a valid xib file
METHOD 1
if you do it with manually, you must check cell is empty or not after dequeueReusableCell check. Just like below,
// create a cell for each table view row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Reuse an old cell if exist else return nil
let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
//check cell is nil if nil you want to allocate it with proper cell
if(cell == nil){
//create cell manually
cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "CellSubtitle")
}
// do stuff to the cell here
return cell
}
METHOD 2
We could create the cell manually like above which is totally fine. But it would be convenient if the table view would create the cell for us directly.
That way we don't have to load it from a nib or instantiate it.
For registering a cell with a xib or class we use func register(AnyClass?, forCellReuseIdentifier: String) method. Let see an example,
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(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
}
You are "registering" your custom Cell class - ItemCell - for reuse as a cell for your tableview.
See: https://developer.apple.com/reference/uikit/uitableview/1614888-register
"Register" tells XCode that the cell exists. A cell is registered under a "reuse identifier." This is a unique string that corresponds to your TableViewCell, in this case ItemCell.
A cell can also be registered in the Storyboard by filling out the "Identifier" in the cell's attributes inspector.

Should conditional binding be used always for dequeuing cell

Inside my cell for row at indexPath, I have been using the following code to do most of my work because that is what I have been taught. I was wondering, is it necessary to always use if let to do this work? Because I never find that I ever fall into the else statement.
When would I need to use if let or just let inside cellForRowAtIndexPath?
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCellWithIdentifier("myCustomCell") as? myCustomCell {
} else {
return myCustomCell()
}
}
UITableView has two dequeue modes:
dequeueReusableCell(withIdentifier:): The table view tries to dequeue a cell. If there are none, it will try to create one using the cell you registered with the reuseIdentifier. If you didn't register a cell, it will return nil giving you the chance to create one yourself.
This is where the else clause in your code would come into effect. Basically never, since presumably you did register a cell class. Most likely in the Storyboard (by setting the identifier in the inspector) but you can also do it in code.
dequeueReusableCell(withIdentifier:for:), note the additional parameter. The table view tries to dequeue a cell: If there are none, it will try to create one using the cell class you registered using the reuseIdentifier. If you didn't register a cell, it will crash.
Solution
If you can guarantee that a) the cell is correctly registered and b) the type of the cell is set correctly, you would generally use the second option. This avoids the exact issue you're having:
let cell = tableView.dequeueReusableCellWithIdentifier("myCustomCell", forIndexPath: indexPath) as! myCustomCell
(However, it is still perfectly fine to use if let even in this case.)

UITableViewCells not displaying first time

I'm trying to create an autocompleter using iOS 8, Swift and Xcode 6.3
I have a problem that I'm trying to solve, but I gave up... I hope someone can help here. The problem is that (custom) UITableViewCell's are not displaying when the initial dataSource is empty. When adding data to datasource and reloading the tableView, the cells SHOULD display, but they don't... At least, the first time they don't... A second time, they DO... When I initialize the table with non-empty data, the problem doesn't occur. I guess something goes wrong with dequeueReusableCellWithIdentifier. In beginning, no reusable cells are found, or something. But I don't know why...
Relevant code, in ViewController.swift:
// filteredWords is a [String] with zero or more items
#IBAction func editingChanged(sender: UITextField) {
autocompleteTableView.hidden = sender.text.isEmpty
filteredWords = dataManager.getFilteredWords(sender.text)
refreshUI()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! AutocompleteTableViewCell
cell.title.text = filteredWords[indexPath.row]
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredWords.count
}
func refreshUI() {
self.autocompleteTableView.reloadData()
}
I created a sample project on github:
https://github.com/dirkpostma/swift-autocomplete
And a movie on YoutTube to show what goes wrong:
https://www.youtube.com/watch?v=ByMsy4AaHYI
Can anyone look at it and spot the bug...?
Thanks in advance!
You've accidentally hidden your cell.
Open Main.storyboard
Select Cell
Uncheck Hidden
Side note: As for why it's displaying the second time around with the cell hidden? It appears to be a bug. It should still be hidden (print cell.hidden, notice it's always true despite showing the text on the screen).
I think you need to change your code. Check out below code. It is because if you remember in Objective C you needed to check if the Cell was nil and then initialise it. The reuse identifier is usually reusing an already created cell, but on the first launch this does not work because there is no Cell to use. Your current code assumes always that the cell is created (re-used) because you are using ! in the declaration, so if you use the optional (?) it can be null and you then can create the cell
var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as? AutocompleteTableViewCell
if cell == nil
{
//You should replace this with your initialisation of custom cell
cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "CELL")
}
cell.title.text = filteredWords[indexPath.row]
return cell

Creating a UITableViewCell programmatically in Swift

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.
In general: Everything is possible in pure programming ;-)
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)
In your custom class for the UITableViewController register the custom cell class using registerClass(forCellReuseIdentifier)
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.
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
}
}

Adding various content type within Table View Cell

I am new to IOS programming and will need some direction here.
I am trying to create a tableview with each rows having a image and some text.
I am able to take a TableViewController and programmatically was able to add basic text and rows. But can you please tell me how should i add more complex content. Trying to achieve something like this using program.
My current code looks like this in my TableViewController and its able to print a text message on each row.
override func numberOfSectionsInTableView(tableView: UITableView!) -> Int {
return 1
}
override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
return 10
}
override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
var mycell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("frontcell", forIndexPath: indexPath) as UITableViewCell
mycell.textLabel.text = "Just a generic message"
return mycell
}
There is a
mycell.contentView
which takes in UIView. But how does it works? How should this object be created?
Appreciate your help.
------Update -----
Thanks to Suryakant for helping out. Answer below for his step by step how to do. Any one who needs the source code can use this. http://pastebin.com/ZfNqK4tW
Though you can achieve it by default UITableViewCell also, as #meda mention in his answer,
but it seems, you want different UIImageView size and 2 UILabels with different font size or may be some more controls there. For Achieving that you need to customize UITableViewCell and you can do that by subclassing UITableViewCell class.
Create a class by subclassing UITableViewCell.
e.g. your subclass say MyCell look like —
2.Go to storyboard and select prototypeCell and select Identity inspector, in Class type your custom class name (e.g MyCell )in place of UITableViewCell.
drag-n-drop all the controls you need and link with their IBOutlets (From MyCell to prototypeCell).
This goes as below..
3.Now goto Attributes Selector and give some Identifier to your MyCell, you can give any string you want.
4.Goto the class where you implemented UITableView delegates and update your cellForIndexPath as bellow
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath:
NSIndexPath!) -> UITableViewCell! {
let kCellIdentifier:String = "cell"
var cell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as MyCell!
if cell == nil {
// register Custom UITableView Class to UITableView
tableView.registerClass(MyCell.classForCoder(), forCellReuseIdentifier: kCellIdentifier)
cell = MyCell(style: UITableViewCellStyle.Default, reuseIdentifier: kCellIdentifier)
}
if var label = cell.cellMyCity{
label.text = cityList[indexPath.row]
}
if var label = cell.cellMyCountry{
label.text = countryList[indexPath.row]
}
if var imageView = cell.imageView{
imageView.image = UIImage(named :"img.png")
}
return cell
}
For reference you can see example code here.
You would create a subclass of UITableViewCell and then assign values to the property of your cell
mycell.textLabel.text = "Just a generic message"
mycell.detailTextLabel.text = "Just a detail message"
mycell.imageView.text = myImage
And for that you would use only one prototype Cell no need to duplicate them.

Resources