Reputation: 57
I am trying to return two different custom cells in the same ViewController
and without any section. Problem comes with method numberOfRowsInTableView
. How do I return the count of the items in two cells? I tried the following code in numberOfRowsInSection
:
var indexPath = NSIndexPath()
if indexPath.row == 2 || indexPath.row == 4 {
return abc.count
} else {
return xyz.count
}
But app crashes with the error :
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid index path for use with UITableView. Index paths passed to table view must contain exactly two indices specifying the section and row. Please use the category on NSIndexPath in UITableView.h if possible.'
Upvotes: 0
Views: 652
Reputation:
For this situation, we cannot return two multiple custom cells count. So for this we need to count elements of both the cells, whose elements are greater, then return that count.
Try this
var abc = [String]() //You can have any datatype of array
var xyz = [String]()
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return (abc.count > xyz.count) ? abc.count : xyz.count
}
Here, to display values in both the custom cells, you need to implement like this way in cellForRowAtIndexPath
function.
func tableView(tableViewData: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableViewData.dequeueReusableCellWithIdentifier("cell")! as! CustomCellClass
if indexPath.row < abc
{
cell.label1.text = abc[indexPath.row]
}
else
{
cell.label1.text = ""
}
if indexPath.row < self.xyz.count
{
cell.label2.text = xyz[indexPath.row]
}
else
{
cell.label2.text = ""
}
return cell
}
Hope it works for you.
Upvotes: 0
Reputation: 25144
If you have only one section, made of two kind of cells coming from two different arrays, then the number of cells in the section is the sum of the two arrays' length. Whatever the order of the cells (be it A, B, A, B, A, B... or A A A A B B B B).
Upvotes: 0
Reputation: 613
If you only have one section then numberOfRowsInSection should return just the total number of cells you will have in your UITableView. If this is fixed, just return the number if it's dynamic (ie. depending on an array) then return the dynamic size (the size of the array).
Upvotes: 1