Test content of a custom TableViewCell - ios

I'm building an iOS application with Swift 2 that uses custom table view cells, with additional labels, image views, etc. (let's call the class CustomTableViewCell). I've made the class-storyboard connections to every subview and assigned an identifier to the cell. I've mocked the data and tried to run the application to check that the cell is properly mapped, and it looks ok.
The problem is that I cannot treat a dequeued cell as a CustomTableViewCell to test the value of its properties. When I downcast the cell returned from tableView(tableView, cellForRowAtIndexPath: indexPath) all custom property values turns into nil and my tests fail.
Here's my code:
MyViewControllerTests.swift
func testShouldConfigureTableViewCellToDisplayNotification() {
// Given
sut.tableView = TableViewSpy()
let items = [ <some items to display> ]
sut.displayedItems = items
// When
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
let cell = viewController.tableView(viewController.tableView, cellForRowAtIndexPath: indexPath) as! CustomTableViewCell
// Then
XCTAssertEqual(cell.detailLabel?.text, "foo", "A properly configured table view cell should display the notification detail")
XCTAssertEqual(cell.titleLabel?.text, "Bar", "A properly configured table view cell should display the notification title")
XCTAssertEqual(cell.dateLabel?.text, "15/04/2016", "A properly configured table view cell should display the notification date")
}
MyViewController.swift
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "CustomTableViewCell"
let displayedItem = displayedItems[indexPath.row]
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? CustomTableViewCell
if cell == nil {
cell = CustomTableViewCell(style: .Value1, reuseIdentifier: cellIdentifier)
}
cell!.dateLabel?.text = displayedItem.date
cell!.detailLabel?.text = displayedItem.detail
cell!.titleLabel?.text = displayedItem.title
return cell!
}
CustomTableViewCell.swift
class CustomTableViewCell: UITableViewCell {
// MARK: Properties
#IBOutlet weak var dateLabel: UILabel!
#IBOutlet weak var detailLabel: UILabel!
#IBOutlet weak var titleLabel: 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
}
}

Try replacing
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "CustomTableViewCell"
let displayedItem = displayedItems[indexPath.row]
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? CustomTableViewCell
if cell == nil {
cell = CustomTableViewCell(style: .Value1, reuseIdentifier: cellIdentifier)
}
cell!.dateLabel?.text = displayedItem.date
cell!.detailLabel?.text = displayedItem.detail
cell!.titleLabel?.text = displayedItem.title
return cell!
}
with
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "CustomTableViewCell"
let displayedItem = displayedItems[indexPath.row]
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as! CustomTableViewCell
cell.dateLabel.text = displayedItem.date
cell.detailLabel.text = displayedItem.detail
cell.titleLabel.text = displayedItem.title
return cell
}
If you have connected your cell correctly ins storyboard then this should work. Otherwise check that you have correctly assigned all IBOutlets for your cell.
If something doesn't work please check the following:
1) Select your cell in the storyboard.
2) In the right column open Identity Inspector (3rd tab at the top). Make sure that the class of your cell is set to CustomTableViewCell.
3) In the Attributes Inspector (4th tab) make sure that cell identifier is correctly spelled.
4) In Connections inspector (last tab) assign all of the IBOutlets of your cell which you have defined.

From your code sample looks like you didn't registered your cell for reusing.
tableView.registerClass(CustomTableViewCell.self, forCellReuseIdentifier: "CustomTableViewCell")

Related

Add UIViews to UIStackView programmatically inside UITableView

I have three elements UILabel, UIImageView and UIButton in a list. I have to show them accordingly inside UITableView. I have an array like this:
tableArray = [["label", "img", "button"],["img","button","label"],["img","label","button"],["button", "img", "label"]]
The positions of the elements are same as the positions of them (index) inside the array. My cellForRowAt looks like this:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "FirstTableViewCell", for: indexPath) as? FirstTableViewCell else {
return UITableViewCell()
}
let tableData = tableArray[indexPath.row]
var count = 0
tableData.forEach { (element) in
switch element {
case "label":
let lbl = self.createLabel()
cell.stackView.insertArrangedSubview(lbl, at: count)
count += 1
break
case "img":
let img = self.createImage()
cell.stackView.insertArrangedSubview(img, at: count)
count += 1
break
case "button":
let btn = self.createButton()
cell.stackView.insertArrangedSubview(btn, at: count)
count += 1
break
default:
break
}
}
return cell
}
The problem is whenever I am scrolling TableView every time those items are added into the cells.
I have tried few solutions to solve that but no luck.
if tableView.cellForRow(at: indexPath) == nil then add elements into stackviews.
Checking if cell == nil after dequeueReusableCell. If nil then init the cell.
let cell = UITableViewCell.init(style: .default, reuseIdentifier: nil) as? FirstTableViewCell tried even without dequeueReusableCell.
But the same thing happens every time.
This is the FirstTableViewCell
class FirstTableViewCell: UITableViewCell {
#IBOutlet weak var stackView: UIStackView!
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
}
}
Any idea how to check if elements are already added to StackView, then I'll not add them.
Because the cells are reused, the first thing you need to do in cellForRowAt is "reset" your cell... in other words, clear out the existing subviews from the stack view:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "FirstTableViewCell", for: indexPath) as? FirstTableViewCell else {
return UITableViewCell()
}
// remove the views that are currently in the stack
cell.stackView.arrangedSubviews.forEach {
$0.removeFromSuperview()
}
// the rest of your setup
let tableData = tableArray[indexPath.row]
var count = 0
tableData.forEach { (element) in
...
}
Now, based on the code you presented, if the cells always contain a UILabel, UIImageView and UIButton, just in different orders and with different properties, you could add them once when you create the cell (or add them in your cell prototype if you're using one), and then simply re-arrange them as needed.

Register UITableViewCell not working

I am trying to register UITableViewCell in viewdidload
self.tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: "CustomTableViewCell")
In cellForRowAtIndex
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell") as! CustomTableViewCell
cell.productNameLabel.text = "Product"
cell.productNameLabel.textColor = UIColor.darkGray
return cell
}
Here it is crashing in cell.productNameLabel.text.
What is the purpose of registering cell? why it is crashing?
I want to reload data even if cell or table is not visible.
Crashreport :
See the Apple's comments which answers your query on the purpose of registering cell :
Prior to dequeueing any cells, call this method or the
register(_:forCellReuseIdentifier:) method to tell the table view how
to create new cells. If a cell of the specified type is not currently
in a reuse queue, the table view uses the provided information to
create a new cell object automatically.
This is the standard procedure I apply while working with Custom Cells (if you are using xib) :
Set cell's identifier in Xib's attribute inspector :
Register Xib :
self.tableTasks.register(UINib(nibName: "TaskCell", bundle: nil), forCellReuseIdentifier: "taskCell")
However, if you are not using Xib and creating custom cell using code only, then use registeCell :
self.tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: "CustomTableViewCell")
Are you using a xib for this cell? If so, none of the outlets will be connected if you just register the class of the cell. You need to register the actual xib file, so that everything can be connected correctly when the cell is created. Have a look at
-(void)registerNib:(UINib *)nib forCellReuseIdentifier:(NSString *)identifier
https://developer.apple.com/documentation/uikit/uitableview/1614937-registernib
My method for register cell.
Syntax sugar
protocol BSCellProtocol {
// For `registerCell`
static var NibName: String! { get }
// For `registerCell`, `dequeueCellWithType`, and `dequeueHeaderFooterWithType`
static var Identifier: String! { get }
}
extension UITableView {
func registerCell(_ type: BSCellProtocol.Type) {
let nib = UINib(nibName: type.NibName, bundle: nil)
let identifier = type.Identifier!
self.register(nib, forCellReuseIdentifier: identifier)
}
func dequeueCellWithType<T: BSCellProtocol>(_ type: T.Type) -> T {
let cell = self.dequeueReusableCell(withIdentifier: type.Identifier) as! T
return cell
}
func dequeueCellWithType<T: BSCellProtocol>(_ type: T.Type, index: IndexPath) -> T {
let cell = self.dequeueReusableCell(withIdentifier: type.Identifier, for: index) as! T
return cell
}
}
Usage
class MyCustomCell: UITableViewCell, BSCellProtocol {
static var NibName: String! = "MyCustomCell"
static var Identifier: String! = "cellIdentifier_at_Xib"
#IBOutlet weak var lblTitle: UILabel!
// other IBOutlet components
}
// In ViewController, register cell
tableView.registerCell(MyCustomCell.self)
// dequeue cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// cell is `MyCustomCell` instance
let cell = tableView.dequeueCellWithType(MyCustomCell.self)
// configure cell ...
// ....
return cell
}
I had the same problem. I also was not using XIB for cell. My view was not connected to View in File's Owner Outlets. Maybe this info will help someone.

How to use the dequeueReuseableCellwithIdentifier method in the UITableViewCell class?

Usually, We use the dequeueReuseableCellwithIdentifier method in ViewController class but I want to use this method in the UITableViewCell.I have tried but I got the exception like this.
fatal error: unexpectedly found nil while unwrapping an optional value
ViewController Class:
#IBOutlet var tableView: UITableView!
var tableData:[songData] = [songData]()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.backgroundColor = UIColor.orangeColor()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = TableViewCell()
cell.datas()
return cell
}
}
TableViewCell Class:
#IBOutlet var text1: UILabel!
#IBOutlet var text2: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func datas(){
let vc = ViewController()
let tableData = vc.tableData
print(tableData)
let tableview = vc.tableView
let indexpath:NSIndexPath = NSIndexPath()
let cell = tableview.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexpath) as! TableViewCell //The fatal error is showing exactly at this line.
let artistAndAlbum = tableData[indexpath.row]
cell.text1.text = artistAndAlbum.country
cell.text2.text = artistAndAlbum.currency
tableview.reloadData()
}
I need to customize my table data in the TableViewCell class.If it is possible help me or else why it is not possible?
You're going about this the wrong way. It honestly doesn't make any sense for your table cell subclass to be creating itself. It does make sense, however, for your cell subclass to be passed data and for it to populate itself from that.
You should have your view controller dequeue the cell as normal and then change your table cell function to take some data as a parameter and update itself.
In your view controller:
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerNib(UINib(nibName: "INSERT_NIB_NAME", bundle: nil), forCellReuseIdentifier: "Cell")
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TableViewCell
cell.updateWithData(tableData[indexPath.row])
return cell
}
If your cell is a prototype cell in the storyboard then you have to set the reuse identifier there instead of registering in viewDidLoad.
In your table cell:
func updateWithData(artistAndAlbum: songData) {
text1.text = artistAndAlbum.country
text2.text = artistAndAlbum.currency
}
In your view controller's viewDidLoad(), register the class with a reuse identifier.
tableView.registerClass(TableViewCell.self, forCellReuseIdentifier: "ID")
Then your cellForRowAtIndexPath method can dequeue your custom cell.
tableView.dequeueReuseableCellWithIdentifier("ID", indexPath: indexPath)
This isn't just limited to view controllers. If you have a custom table view cell, then register the class for a reuse identifier wherever you setup the table view and then dequeue your custom cell with that identifier in its cellForRowAtIndexPath.
As a general rule of thumb, your view should not keep a reference to its view controller. The view shouldn't care about any view controllers or need to know what the view controller is doing. Either the entire table view and all of its workings should go in your view, hidden from the view controller, or you should keep all of your table view code in the view controller. This will make your life much easier.
Firstly you must set name for cell identifier
after it in cellForRowAtIndexPath method used this code:-
for custom cell
CustomCellTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"CELL" forIndexPath:indexPath];
//-------------------------------------------------------------
for normal cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"CELL" forIndexPath:indexPath];
Check your vc.tableView. It's probably nil

Set checkmark for static table view cell

I have an iPhone app with iOS 8 and Swift.
I would like to set the checkmark accessory in a static table view with 3 rows. I use NSUserdefaults where I save a string. For the checkmark I use this code:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var identifier = defaults.objectForKey("Sort") as! String
let cell = tableView.dequeueReusableCellWithIdentifier("\(identifier)") as! UITableViewCell
cell.accessoryType = UITableViewCellAccessoryType.Checkmark
return cell
}
But it doesn't work. I always get the error:
fatal error: unexpectedly found nil while unwrapping an Optional value
on this line:
let cell = tableView.dequeueReusableCellWithIdentifier(identifier) as! UITableViewCell
I did not forget to set the cell identifier in the storyboard.
Since you are using static cells, in which case you only have 3, you could set up IBOutlet in storyboard.
#IBOutlet weak var cell1: UITableViewCell!
#IBOutlet weak var cell2: UITableViewCell!
#IBOutlet weak var cell3: UITableViewCell!
Subsequently, while you are still in storyboard, please set up tags for each cell, by clicking on the Attributes Inspector on the right.
For test, I set up the tags from 0 - 2 (i.e., 0, 1, 2).
I am guessing that you are saving a String value in you main controller, and once clicked, you would like so that the corresponding cell would have a checkmark by getting that value out of NSDefault again.
You could do this in method (Swift-wise: function):
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath)
Here is what I came up as a quick test:
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath)
{
NSUserDefaults.standardUserDefaults().setObject("0", forKey: "Sort")
NSUserDefaults.standardUserDefaults().synchronize()
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
var aString = defaults.valueForKey("Sort") as? String
let cellIndex = aString?.toInt()
if cell1.tag == cellIndex
{
cell1.textLabel!.text = "Hallo, I am cell 1"
cell1.accessoryType = UITableViewCellAccessoryType.Checkmark
}
else if cell2.tag == cellIndex
{
cell2.textLabel!.text = "Hello, I am cell 2"
cell2.accessoryType = UITableViewCellAccessoryType.Checkmark
}
else if cell3.tag == cellIndex
{
cell3.textLabel!.text = "Hello, I am cell 3"
cell3.accessoryType = UITableViewCellAccessoryType.Checkmark
}
}
As test, I set it as 0 and get it back immediately from NSDefault; and the first cell is checked with a checkmark.
If you use static table view cells, tableView.dequeueReusableCellWithIdentifier will always return nil. This causes the error.
As an alternative, you can set the checkmars in the viewWillAppear function. There, you can access the cells via the tableView.cellForRowAtIndexPath function:
override func viewWillAppear(_ animated: bool) {
super.viewWillAppear(animated)
let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0)) as UITableViewCell
cell.accessoryType = UITableViewCellAccessoryType.Checkmark
...
}
(replace the values of the forRow and inSection parameters as you need)

TableViewCell overlaps text

I'm having a problem with my TableViewCell
I have two type of cell in my storyboard.
when i scroll, the text overlaps in some cells. I Try everything but I do not know how else to do. thank you very much for the help
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var storeNew = systemsBlog.getStore(listNews[indexPath.row].getIdStore())
var newNotice = listNews[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier("TimelineCell", forIndexPath: indexPath) as? TimelineCell
cell!.nameLabel.text = storeNew.getName()
cell!.postLabel?.text = newNotice.getText()
cell!.postLabel?.numberOfLines = 0
cell!.dateLabel.text = newNotice.getDate()
cell!.typeImageView?.tag = indexPath.row;
return cell!
}
class TimelineCell : UITableViewCell {
#IBOutlet var nameLabel : UILabel!
#IBOutlet var postLabel : UILabel?
#IBOutlet var dateLabel : UILabel!
override func awakeFromNib() {
postLabel?.font = UIFont(name: "Roboto-Thin", size: 14)
}
override func layoutSubviews() {
super.layoutSubviews()
}
I can fix the problem. In the storyboard, the label have unchacked "Clears Graphics Context". I checked and for now it solved! Thanks for the help!
I had a similar issue with one of my UITableViews in the past. There are a bunch of things that could cause this, but maybe it is the same thing that happened to me.
I see that you are using a custom tableViewCell. What could be happening is when you set the text of the cell, it adds a label view with that text. Now say you scroll through the tableview and that cell disappears. If you were to reuse that cell and you did not remove the label from the subview, or set the text of that label again to the desired text, you will be reusing the tableviewcell with a previous label on it and adding a new label with new text to it, overlapping the text.
My suggestion would be to make sure you do not keep adding UIlabels as subviews in the TimelineCell class unless no label exists. if a label exists edit the text of that label not of the cell.
As per apple documentation:
The table view’s data source implementation of
tableView:cellForRowAtIndexPath: should always reset all content when
reusing a cell.
It seems that your problem is that you not always setting postLabel, causing it to write on top of the other cells, try this:
//reuse postLabel and set to blank it no value is returned by the function
let cell = tableView.dequeueReusableCellWithIdentifier("TimelineCell", forIndexPath: indexPath) as? TimelineCell
cell!.nameLabel.text = storeNew.getName()
if newNotice.getText() != nil{
cell!.postLabel.text = newNotice.getText()
} else {cell!.postLabel.text = ''}
cell!.postLabel.numberOfLines = 0
cell!.dateLabel.text = newNotice.getDate()
cell!.typeImageView?.tag = indexPath.row;
return cell!
}
//Make postLabel mandatory and set the font details in the xcode
class TimelineCell : UITableViewCell {
#IBOutlet var nameLabel : UILabel!
#IBOutlet var postLabel : UILabel!
#IBOutlet var dateLabel : UILabel!
override func awakeFromNib() {
//set this in xcode
}
override func layoutSubviews() {
super.layoutSubviews()
}
Also be sure that you are not creating any UI element and appending to the cell, as if you are you need to dispose it before you recycle the cell.
You can try setting:
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 44.0 // Set this value as a good estimation according to your cells
}
In the View Controller containing your tableView.
Make sure the layout constraints in your TimelineCell define a clear line of height constraints
Another option is responding to:
tableView(_ tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 44.0 // Your height depending on the indexPath
}
Always in the ViewController that contains your tableView and, I assume, is the tableView's UITableViewDelegate
Hope this helps
Set cell to nil that will fix some error.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
var cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as? ImageCellTableViewCell
cell = nil
if cell == nil {
cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for:indexPath) as? ImageCellTableViewCell
}
cell.yourcoustomtextTextLabel.text = "this is text"
cell.yourcoustomtextImageView.image = image
return cell
}

Resources