How to detect the last cell - ios

This table view delegate code to detect the last table cell doesn't work.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if (indexPath.row == self.tableView(tableView, numberOfRowsInSection: 0) - 1) {
...
}
}
The "last row" as determined by the code moves up and down the list as I scroll. How do I fix this?

I think the number of the sections for the tableView is more than 1,so you need to take the section into calculation(you should make sure that numberOfSections and numberOfRows is greater than 0):
let numberOfSections = self.tableView.numberOfSections
let numberOfRows = self.tableView.numberOfRowsInSection(numberOfSections-1)
if indexPath.row == numberOfRows - 1 && indexPath.section == numberOfSections - 1{
...
}

Try the below code
if (indexPath == [NSIndexPath indexPathForRow:(numberOfRowsInLastSection - 1) inSection:(numberOfSections - 1)])
{
...
}

In some cases, your last section might be empty, so you want to look for the section last section which contains a cell. This can be done by looping over each section, and in each section loop over each cell. While doing this, keep track of the last indexPath of the cell you encountered, and when the loop is done, you can retrieve the last cell using the indexPath.
Something like this should work:
NSIndexPath *lastCellIndexPath;
for (NSInteger sectionIndex = self.tableView.numberOfSections - 1; sectionIndex >= 0; sectionIndex--) {
if ([self.tableView numberOfRowsInSection:sectionIndex] > 0) {
NSInteger section = sectionIndex;
NSInteger row = [self.tableView numberOfRowsInSection:sectionIndex] - 1;
lastCellIndexPath = [NSIndexPath indexPathForRow:row inSection:section];
break;
}
}
// Retrieve your cell with the indexPath
...

My cell contains a UIView that draws inside drawRect and the output is different for the starting and ending table cells. I've found that if I do the following...
cell!.contLine.setNeedsDisplay()
...then the drawing is correct. (contLine is the embedded UIView). If I call setNeedsDisplay on the cell then it doesn't work. So I'm having to break encapsulation here.
As a result of Ossie's suggestion, I've also changed the detection code so that it updates the state of the cell every time. Otherwise, a reused cell's state can be stale.
cell!.isEnd = (indexPath.row == (self.tableView(tableView, numberOfRowsInSection: 0) - 1))

Related

How do I get the last indexPath of a uicollectionview (NOT TABLE VIEW) ? Need it do server side paging

I have looked for ways of getting the last indexPath of a UICollectionView, although below code works for a UITableView (having one section):
[NSIndexPath indexPathForRow:[yourArray count]-1 inSection:0]
but not been able to achieve the same thing for a UICollectionView.
You can find last index of UICollectionView like this.
NSInteger lastSectionIndex = MAX(0, [self.yourCollectionView numberOfSections] - 1);
NSInteger lastRowIndex = MAX(0, [self.yourCollectionView numberOfItemsInSection:lastSectionIndex] - 1);
NSIndexPath *lastIndexPath = [NSIndexPath indexPathForRow:lastRowIndex
inSection:lastSectionIndex];
You can also find last index of UITableView like this.
NSInteger lastSectionIndex = MAX(0, [self.yourTableView numberOfSections] - 1);
NSInteger lastRowIndex = MAX(0, [self.yourTableView numberOfRowsInSection:lastSectionIndex] - 1);
NSIndexPath *lastIndexPath = [NSIndexPath indexPathForRow:lastRowIndex
inSection:lastSectionIndex];
And if you want to detect last index of a specific section, you just need to replace the index of that section with "lastSectionIndex".
Simple way for the server side paging (that I use):
You can do the server side paging in willDisplay cell: delegate method of the collection/table view both.
You'll get the indexPath of the cell that's going to display then make a condition that will check that the showing indexPath.item is equal to the dataArray.count-1 (dataArray is an array from which your collection/table view is loaded)
i think,
you should do it in scrollView's Delegate "scrollViewDidEndDecelerating",
check your currently visible cells by
NSArray<NSIndexPath*>* visibleCells = [self.collection indexPathsForVisibleItems];
create last indexPath by,
NSIndexPath* lastIndexPath = [NSIndexPath indexPathForItem:(datasource.count-1) inSection:0];
check conditions,
if([visibleCells containsObject:lastIndexPath]) {
//This means you reached at last of your datasource. and here you can do load more process from server
}
whole code will be like, Objective C Code,
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
NSArray<NSIndexPath*>* visibleCells = [collection indexPathsForVisibleItems];
NSIndexPath* lastIndexPath = [NSIndexPath indexPathForItem:(Blogs.count - 1) inSection:0];
if([visibleCells containsObject:lastIndexPath]) {
//This means you reached at last of your datasource. and here you can do load more process from server
}
}
Swift 3.1 Code,
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let visibleCells: [IndexPath] = collection.indexPathsForVisibleItems
let lastIndexPath = IndexPath(item: (Blogs.count - 1), section: 0)
if visibleCells.contains(lastIndexPath) {
//This means you reached at last of your datasource. and here you can do load more process from server
}
}
Swift 5
extension UICollectionView {
func getLastIndexPath() -> IndexPath {
let lastSectionIndex = max(0, self.numberOfSections - 1)
let lastRowIndex = max(0, self.numberOfItems(inSection: lastSectionIndex) - 1)
return IndexPath(row: lastRowIndex, section: lastSectionIndex)
}
}

UITableView: highlight the last cell but other cells get highlighted as well

I have UITableView that I use as a sliding menu as part of SWRevealViewController.
I want to select the last cell in UITableView and implement the following:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let customCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! IGAWindAloftMenuTableViewCell
...
let sectionsAmount = tableView.numberOfSections
let rowsAmount = tableView.numberOfRowsInSection(indexPath.section)
if (indexPath.section == sectionsAmount - 1 && indexPath.row == rowsAmount - 1)
{
customCell.backgroundColor = UIColor.yellowColor()
}
return customCell
}
When I scroll all the way down, it works -- the last cell is highlighted. However, when I scroll up and down, other cells in the middle of the table get highlighted as well.
Is there any way to prevent it?
Thank you!
You have to undo the change made in the if-branch for all other cells:
if (indexPath.section == sectionsAmount - 1 && indexPath.row == rowsAmount - 1) {
customCell.backgroundColor = UIColor.yellowColor()
} else {
customCell.backgroundColor = UIColor.whiteColor() // or whatever color
}
The reason for the undesired side effect is the reusing of cells. A cell gets created, then it gets used as the last cell, then it moves off-screen and is reused somewhere else. It still contains the changed color information but is no longer at the corresponding position.

Remove All Cell Accessories in UITableView in Swift 2

I have a method in Objective-C that I've used to uncheck all cells in a UITableView:
- (void)resetCheckedCells {
for (NSUInteger section = 0, sectionCount = self.tableView.numberOfSections; section < sectionCount; ++section) {
for (NSUInteger row = 0, rowCount = [self.tableView numberOfRowsInSection:section]; row < rowCount; ++row) {
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:section]];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.accessoryView = nil;
}
}
}
In Swift, I think I need to use enumeration to accomplish this. I'm stumped as to how to get the values I need. Here's a "physics for poets" sketch of what I'm trying to do:
func resetCheckedCells() {
// TODO: figure this out?
for (section, tableView) in tableView.enumerate() {
for (row, tableView) in tableView {
let cell = UITableView
cell.accessoryType = .None
}
}
}
This doesn't work, but it's illustrative of what I'm trying to accomplish. What am I missing?
UPDATE
There was a very simple, but non-apparent (to me), way to do this involving cellForRowAtIndexPath and a global array...
var myStuffToSave = [NSManagedObject]()
... that's instantiated with the UITableViewController loads. I'm posting this update in hopes that someone else might find it helpful.
My UITableViewController is initially populated with NSManagedObjects. My didSelectRowAtIndexPath does two things:
1) adds/removes NSManagedObjects from a global myStuffToSave array
2) toggles cell.accessoryType for the cell between .Checkmark and .None
That when cellForRowAtIndexPath is called, I compare items from myStuffToSave with what's in the tableView.
Here's a snippet of my cellForRowAtIndexPath:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
// I set the cells' accessory types to .None when they're drawn
// ** SO RELOADING THE tableView NUKES THE CHECKMARKS WITH THE FOLLOWING LINE... **
cell.accessoryType = .None
// boilerplate cell configuration
// Set checkmarks
// ** ...IF THE ARRAY IS EMPTY
if self.myStuffToSave.count > 0 {
// enumerate myStuffToSave...
for (indexOfMyStuffToSave, thingToSave) in stuffToSave.enumerate() {
// if the object in the array of stuff to save matches the object in the index of the tableview
if stuffInMyTableView[indexPath.row].hashValue == stuffToSave[indexOfMyStuffToSave].hashValue {
// then set its accessoryView to checkmark
cell.accessoryType = .Checkmark
}
}
}
return cell
}
So removing everything from myStuffToSave and reloading the tableView will reset all the checked cells. This is what my resetCheckedCells method looks like at the end:
func resetCheckedCells() {
// remove everything from myStuffToSave
self.myStuffToSave.removeAll()
// and reload tableView where the accessoryType is set to .None by default
self.tableView.reloadData()
}
Thanks to #TannerNelson for pointing me towards a solution.
This seems like a strange way to use UITableView.
You should look at the UITableViewDataSource protocol and implement your code using that.
The main function you will need to implement is tableView:cellForRowAtIndexPath. In this function, you dequeue and return a cell.
Then when you need to update cells to be checked or unchecked, you can just call reloadAtIndexPaths: and pass the visible index paths.
This gist has a nice UITableView extension for reloading only visible cells using self.tableView.reloadVisibleCells()
https://gist.github.com/tannernelson/6d140c5ce2a701e4b710

UITableView set to static cells. Is it possible to hide some of the cells programmatically?

UITableView set to static cells.
Is it possible to hide some of the cells programmatically?
To hide static cells in UITable:
Add this method:
In your UITableView controller delegate class:
Objective-C:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell* cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
if(cell == self.cellYouWantToHide)
return 0; //set the hidden cell's height to 0
return [super tableView:tableView heightForRowAtIndexPath:indexPath];
}
Swift:
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
var cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath)
if cell == self.cellYouWantToHide {
return 0
}
return super.tableView(tableView, heightForRowAtIndexPath: indexPath)
}
This method will get called for each cell in the UITable. Once it calls it for the cell you want to hide, we set its height to 0. We identify the target cell by creating an outlet for it:
In the designer, create an outlet for the cell(s) you want to hide. The outlet for one such cell is called "cellYouWantToHide" above.
Check "Clip Subviews" in the IB for the cells you want to hide. The cells you are hiding need to have ClipToBounds = YES. Otherwise the text will pile up in the UITableView.
You are looking for this solution :
StaticDataTableViewController 2.0
https://github.com/xelvenone/StaticDataTableViewController
which can show/hide/reload any static cell(s) with or without animation!
[self cell:self.outletToMyStaticCell1 setHidden:hide];
[self cell:self.outletToMyStaticCell2 setHidden:hide];
[self reloadDataAnimated:YES];
Note to always use only (reloadDataAnimated:YES/NO)
(dont call [self.tableView reloadData] directly)
This doesn't use the hacky solution with setting height to 0 and allows you to animate the change and hide whole sections
The best way is as described in the following blog
http://ali-reynolds.com/2013/06/29/hide-cells-in-static-table-view/
Design your static table view as normal in interface builder –
complete with all potentially hidden cells. But there is one thing you
must do for every potential cell that you want to hide – check the
“Clip subviews” property of the cell, otherwise the content of the
cell doesn’t disappear when you try and hide it (by shrinking it’s
height – more later).
SO – you have a switch in a cell and the switch is supposed to hide
and show some static cells. Hook it up to an IBAction and in there do
this:
[self.tableView beginUpdates];
[self.tableView endUpdates];
That gives you nice animations for the cells appearing and
disappearing. Now implement the following table view delegate method:
- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.section == 1 && indexPath.row == 1) { // This is the cell to hide - change as you need
// Show or hide cell
if (self.mySwitch.on) {
return 44; // Show the cell - adjust the height as you need
} else {
return 0; // Hide the cell
}
}
return 44;
}
And that’s it. Flip the switch and the cell hides and reappears with a
nice, smooth animation.
My solution goes into a similar direction as Gareth, though I do some things differently.
Here goes:
1. Hide the cells
There is no way to directly hide the cells. UITableViewController is the data source which provides the static cells, and currently there is no way to tell it "don't provide cell x".
So we have to provide our own data source, which delegates to the UITableViewController in order to get the static cells.
Easiest is to subclass UITableViewController, and override all methods which need to behave differently when hiding cells.
In the simplest case (single section table, all cells have the same height), this would go like this:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [super tableView:tableView numberOfRowsInSection:section] - numberOfCellsHidden;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Recalculate indexPath based on hidden cells
indexPath = [self offsetIndexPath:indexPath];
return [super tableView:tableView cellForRowAtIndexPath:indexPath];
}
- (NSIndexPath*)offsetIndexPath:(NSIndexPath*)indexPath
{
int offsetSection = indexPath.section; // Also offset section if you intend to hide whole sections
int numberOfCellsHiddenAbove = ... // Calculate how many cells are hidden above the given indexPath.row
int offsetRow = indexPath.row + numberOfCellsHiddenAbove;
return [NSIndexPath indexPathForRow:offsetRow inSection:offsetSection];
}
If your table has multiple sections, or the cells have differing heights, you need to override more methods. The same principle applies here: You need to offset indexPath, section and row before delegating to super.
Also keep in mind that the indexPath parameter for methods like didSelectRowAtIndexPath: will be different for the same cell, depending on state (i.e. the number of cells hidden). So it is probably a good idea to always offset any indexPath parameter and work with these values.
2. Animate the change
As Gareth already stated, you get major glitches if you animate changes using reloadSections:withRowAnimation: method.
I found out that if you call reloadData: immediately afterwards, the animation is much improved (only minor glitches left). The table is displayed correctly after the animation.
So what I am doing is:
- (void)changeState
{
// Change state so cells are hidden/unhidden
...
// Reload all sections
NSIndexSet* reloadSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [self numberOfSectionsInTableView:tableView])];
[tableView reloadSections:reloadSet withRowAnimation:UITableViewRowAnimationAutomatic];
[tableView reloadData];
}
In the designer, create an outlet for the cell(s) you want to hide. For example you want to hide 'cellOne', so in viewDidLoad() do this
cellOneOutlet.hidden = true
now override the below method, check which cell status is hidden and return height 0 for those cell(s). This is one of many ways you can hide any cell in static tableView in swift.
override func tableView(tableView: UITableView, heightForRowAtIndexPathindexPath: NSIndexPath) -> CGFloat
{
let tableViewCell = super.tableView(tableView,cellForRowAtIndexPath: indexPath)
if tableViewCell.hidden == true
{
return 0
}
else{
return super.tableView(tableView, heightForRowAtIndexPath: indexPath)
}
}
I came up with an alternative that actually hides sections and doesn't delete them. I tried #henning77's approach, but I kept running into problems when I changed the number of sections of the static UITableView. This method has worked really well for me, but I'm primarily trying to hide sections instead of rows. I am removing some rows on the fly successfully, but it is a lot messier, so I've tried to group things into sections that I need to show or hide. Here is an example of how I'm hiding sections:
First I declare a NSMutableArray property
#property (nonatomic, strong) NSMutableArray *hiddenSections;
In the viewDidLoad (or after you have queried your data) you can add sections you want to hide to the array.
- (void)viewDidLoad
{
hiddenSections = [NSMutableArray new];
if(some piece of data is empty){
// Add index of section that should be hidden
[self.hiddenSections addObject:[NSNumber numberWithInt:1]];
}
... add as many sections to the array as needed
[self.tableView reloadData];
}
Then implement the following the TableView delegate methods
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
if([self.hiddenSections containsObject:[NSNumber numberWithInt:section]]){
return nil;
}
return [super tableView:tableView titleForHeaderInSection:section];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if([self.hiddenSections containsObject:[NSNumber numberWithInt:indexPath.section]]){
return 0;
}
return [super tableView:tableView heightForRowAtIndexPath:[self offsetIndexPath:indexPath]];
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if([self.hiddenSections containsObject:[NSNumber numberWithInt:indexPath.section]]){
[cell setHidden:YES];
}
}
Then set the header and footer height to 1 for hidden sections because you can't set the height to 0. This causes an additional 2 pixel space, but we can make up for it by adjusting the height of the next visible header.
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
CGFloat height = [super tableView:tableView heightForHeaderInSection:section];
if([self.hiddenSections containsObject:[NSNumber numberWithInt:section]]){
height = 1; // Can't be zero
}
else if([self tableView:tableView titleForHeaderInSection:section] == nil){ // Only adjust if title is nil
// Adjust height for previous hidden sections
CGFloat adjust = 0;
for(int i = (section - 1); i >= 0; i--){
if([self.hiddenSections containsObject:[NSNumber numberWithInt:i]]){
adjust = adjust + 2;
}
else {
break;
}
}
if(adjust > 0)
{
if(height == -1){
height = self.tableView.sectionHeaderHeight;
}
height = height - adjust;
if(height < 1){
height = 1;
}
}
}
return height;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
if([self.hiddenSections containsObject:[NSNumber numberWithInt:section]]){
return 1;
}
return [super tableView:tableView heightForFooterInSection:section];
}
Then, if you do have specific rows to hide you can adjust the numberOfRowsInSection and which rows are returned in cellForRowAtIndexPath. In this example here I have a section that has three rows where any three could be empty and need to be removed.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger rows = [super tableView:tableView numberOfRowsInSection:section];
if(self.organization != nil){
if(section == 5){ // Contact
if([self.organization objectForKey:#"Phone"] == [NSNull null]){
rows--;
}
if([self.organization objectForKey:#"Email"] == [NSNull null]){
rows--;
}
if([self.organization objectForKey:#"City"] == [NSNull null]){
rows--;
}
}
}
return rows;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [super tableView:tableView cellForRowAtIndexPath:[self offsetIndexPath:indexPath]];
}
Use this offsetIndexPath to calculate the indexPath for rows where you are conditionally removing rows. Not needed if you are only hiding sections
- (NSIndexPath *)offsetIndexPath:(NSIndexPath*)indexPath
{
int row = indexPath.row;
if(self.organization != nil){
if(indexPath.section == 5){
// Adjust row to return based on which rows before are hidden
if(indexPath.row == 0 && [self.organization objectForKey:#"Phone"] == [NSNull null] && [self.organization objectForKey:#"Email"] != [NSNull null]){
row++;
}
else if(indexPath.row == 0 && [self.organization objectForKey:#"Phone"] == [NSNull null] && [self.organization objectForKey:#"Address"] != [NSNull null]){
row = row + 2;
}
else if(indexPath.row == 1 && [self.organization objectForKey:#"Phone"] != [NSNull null] && [self.organization objectForKey:#"Email"] == [NSNull null]){
row++;
}
else if(indexPath.row == 1 && [self.organization objectForKey:#"Phone"] == [NSNull null] && [self.organization objectForKey:#"Email"] != [NSNull null]){
row++;
}
}
}
NSIndexPath *offsetPath = [NSIndexPath indexPathForRow:row inSection:indexPath.section];
return offsetPath;
}
There are a lot of methods to override, but what I like about this approach is that it is re-usable. Setup the hiddenSections array, add to it, and it will hide the correct sections. Hiding the rows it a little trickier, but possible. We can't just set the height of the rows we want to hide to 0 if we're using a grouped UITableView because the borders will not get drawn correctly.
Turns out, you can hide and show cells in a static UITableView - and with animation. And it is not that hard to accomplish.
Demo project
Demo project video
The gist:
Use tableView:heightForRowAtIndexPath: to specify cell heights dynamically based on some state.
When the state changes animate cells showing/hiding by calling tableView.beginUpdates();tableView.endUpdates()
Do not call tableView.cellForRowAtIndexPath: inside tableView:heightForRowAtIndexPath:. Use cached indexPaths to differentiate the cells.
Do not hide cells. Set "Clip Subviews" property in Xcode instead.
Use Custom cells (not Plain etc) to get a nice hiding animation. Also, handle Auto Layout correctly for the case when cell height == 0.
More info in my blog (Russian language)
As per Justas's answer, but for Swift 4:
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let cell = super.tableView(tableView, cellForRowAt: indexPath)
if cell == self.cellYouWantToHide {
return 0
}
return super.tableView(tableView, heightForRowAt: indexPath)
}
Yes, it's definitely possible, although I am struggling with the same issue at the moment. I've managed to get the cells to hide and everything works ok, but I cannot currently make the thing animate neatly. Here is what I have found:
I am hiding rows based on the state of an ON / OFF switch in the first row of the first section. If the switch is ON there is 1 row beneath it in the same section, otherwise there are 2 different rows.
I have a selector called when the switch is toggled, and I set a variable to indicate which state I am in. Then I call:
[[self tableView] reloadData];
I override the tableView:willDisplayCell:forRowAtIndexPath: function and if the cell is supposed to be hidden I do this:
[cell setHidden:YES];
That hides the cell and its contents, but does not remove the space it occupies.
To remove the space, override the tableView:heightForRowAtIndexPath: function and return 0 for rows that should be hidden.
You also need to override tableView:numberOfRowsInSection: and return the number of rows in that section. You have to do something strange here so that if your table is a grouped style the rounded corners occur on the correct cells. In my static table there is the full set of cells for the section, so there is the first cell containing the option, then 1 cell for the ON state options and 2 more cells for the OFF state options, a total of 4 cells. When the option is ON, I have to return 4, this includes the hidden option so that the last option displayed has a rounded box. When the option is off, the last two options are not displayed so I return 2. This all feels clunky. Sorry if this isn't very clear, its tricky to describe. Just to illustrate the setup, this is the construction of the table section in IB:
Row 0: Option with ON / OFF switch
Row 1: Displayed when option is ON
Row 2: Displayed when option is OFF
Row 3: Displayed when option is OFF
So when the option is ON the table reports two rows which are:
Row 0: Option with ON / OFF switch
Row 1: Displayed when option is ON
When the option is OFF the table reports four rows which are:
Row 0: Option with ON / OFF switch
Row 1: Displayed when option is ON
Row 2: Displayed when option is OFF
Row 3: Displayed when option is OFF
This approach doesn't feel correct for several reasons, its just as far as I have got with my experimentation so far, so please let me know if you find a better way. The problems I have observed so far are:
It feels wrong to be telling the table the number of rows is different to what is presumably contained in the underlying data.
I can't seem to animate the change. I've tried using tableView:reloadSections:withRowAnimation: instead of reloadData and the results don't seem to make sense, I'm still trying to get this working. Currently what seems to happen is the tableView does not update the correct rows so one remains hidden that should be displayed and a void is left under the first row. I think this might be related to the first point about the underlying data.
Hopefully someone will be able to suggest alternative methods or perhaps how to extend with animation, but maybe this will get you started. My apologies for the lack of hyperlinks to functions, I put them in but they were rejected by the spam filter because I am a fairly new user.
Okay, after some trying, I have a non common answer.
I am using the "isHidden" or "hidden" variable to check if this cell should be hidden.
create an IBOutlet to your view controller.
#IBOutlet weak var myCell: UITableViewCell!
Update the myCell in your custom function, example you may add it in viewDidLoad:
override func viewDidLoad() {
super.viewDidLoad()
self.myCell.isHidden = true
}
in your delegate method:
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let cell = super.tableView(tableView, cellForRowAt: indexPath)
guard !cell.isHidden else {
return 0
}
return super.tableView(tableView, heightForRowAt: indexPath)
}
This will reduce your logic in the delegate method, and you only need to focus on your business requirement.
Simple iOS 11 & IB/Storyboard Compatible Method
For iOS 11, I found that a modified version of Mohamed Saleh's answer worked best, with some improvements based on Apple's documentation. It animates nicely, avoids any ugly hacks or hardcoded values, and uses row heights already set in Interface Builder.
The basic concept is to set the row height to 0 for any hidden rows. Then use tableView.performBatchUpdates to trigger an animation that works consistently.
Set the cell heights
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath == indexPathOfHiddenCell {
if cellIsHidden {
return 0
}
}
// Calling super will use the height set in your storyboard, avoiding hardcoded values
return super.tableView(tableView, heightForRowAt: indexPath)
}
You'll want to make sure cellIsHidden and indexPathOfHiddenCell are set appropriately to your use case. For my code they're properties on my table view controller.
Toggling the cell
In whatever method controls the visibility (likely a button action or didSelectRow), toggle the cellIsHidden state, inside a performBatchUpdates block:
tableView.performBatchUpdates({
// Use self to capture for block
self.cellIsHidden = !self.cellIsHidden
}, completion: nil)
Apple recommends performBatchUpdates over beginUpdates/endUpdates whenever possible.
The above answers that hide/show cells, change rowHeight, or mess with Auto layout constraints didn't work for me because of Auto layout issues. The code became intolerable.
For a simple static table, what worked best for me was to:
Create an outlet for every cell in the static table
Create an array only with the outlets of cells to show
Override cellForRowAtIndexPath to return the cell from the array
Override numberOfRowsInSection to return the count of the array
Implement a method to determine what cells need to be in that array, and call that method whenever needed, and then reloadData.
Here is an example from my table view controller:
#IBOutlet weak var titleCell: UITableViewCell!
#IBOutlet weak var nagCell: UITableViewCell!
#IBOutlet weak var categoryCell: UITableViewCell!
var cellsToShow: [UITableViewCell] = []
override func viewDidLoad() {
super.viewDidLoad()
determinCellsToShow()
}
func determinCellsToShow() {
if detail!.duration.type != nil {
cellsToShow = [titleCell, nagCell, categoryCell]
}
else {
cellsToShow = [titleCell, categoryCell]
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return cellsToShow[indexPath.row]
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellsToShow.count
}
I found a solution for animate hiding cells in static table.
// Class for wrapping Objective-C block
typedef BOOL (^HidableCellVisibilityFunctor)();
#interface BlockExecutor : NSObject
#property (strong,nonatomic) HidableCellVisibilityFunctor block;
+ (BlockExecutor*)executorWithBlock:(HidableCellVisibilityFunctor)block;
#end
#implementation BlockExecutor
#synthesize block = _block;
+ (BlockExecutor*)executorWithBlock:(HidableCellVisibilityFunctor)block
{
BlockExecutor * executor = [[BlockExecutor alloc] init];
executor.block = block;
return executor;
}
#end
Only one additional dictionary needed:
#interface MyTableViewController ()
#property (nonatomic) NSMutableDictionary * hidableCellsDict;
#property (weak, nonatomic) IBOutlet UISwitch * birthdaySwitch;
#end
And look at implementation of MyTableViewController. We need two methods to convert indexPath between visible and invisible indexes...
- (NSIndexPath*)recoverIndexPath:(NSIndexPath *)indexPath
{
int rowDelta = 0;
for (NSIndexPath * ip in [[self.hidableCellsDict allKeys] sortedArrayUsingSelector:#selector(compare:)])
{
BlockExecutor * executor = [self.hidableCellsDict objectForKey:ip];
if (ip.section == indexPath.section
&& ip.row <= indexPath.row + rowDelta
&& !executor.block())
{
rowDelta++;
}
}
return [NSIndexPath indexPathForRow:indexPath.row+rowDelta inSection:indexPath.section];
}
- (NSIndexPath*)mapToNewIndexPath:(NSIndexPath *)indexPath
{
int rowDelta = 0;
for (NSIndexPath * ip in [[self.hidableCellsDict allKeys] sortedArrayUsingSelector:#selector(compare:)])
{
BlockExecutor * executor = [self.hidableCellsDict objectForKey:ip];
if (ip.section == indexPath.section
&& ip.row < indexPath.row - rowDelta
&& !executor.block())
{
rowDelta++;
}
}
return [NSIndexPath indexPathForRow:indexPath.row-rowDelta inSection:indexPath.section];
}
One IBAction on UISwitch value changing:
- (IBAction)birthdaySwitchChanged:(id)sender
{
NSIndexPath * indexPath = [self mapToNewIndexPath:[NSIndexPath indexPathForRow:1 inSection:1]];
if (self.birthdaySwitch.on)
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
else
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
Some UITableViewDataSource and UITableViewDelegate methods:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int numberOfRows = [super tableView:tableView numberOfRowsInSection:section];
for (NSIndexPath * indexPath in [self.hidableCellsDict allKeys])
if (indexPath.section == section)
{
BlockExecutor * executor = [self.hidableCellsDict objectForKey:indexPath];
numberOfRows -= (executor.block()?0:1);
}
return numberOfRows;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
indexPath = [self recoverIndexPath:indexPath];
return [super tableView:tableView cellForRowAtIndexPath:indexPath];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
indexPath = [self recoverIndexPath:indexPath];
return [super tableView:tableView heightForRowAtIndexPath:indexPath];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// initializing dictionary
self.hidableCellsDict = [NSMutableDictionary dictionary];
[self.hidableCellsDict setObject:[BlockExecutor executorWithBlock:^(){return self.birthdaySwitch.on;}] forKey:[NSIndexPath indexPathForRow:1 inSection:1]];
}
- (void)viewDidUnload
{
[self setBirthdaySwitch:nil];
[super viewDidUnload];
}
#end
Answer in swift:
Add the following method in your TableViewController:
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return indexPathOfCellYouWantToHide == indexPath ? 0 : super.tableView(tableView, heightForRowAtIndexPath: indexPath)
}
if the tableView tries to draw the cell you wish to hide, then it won't display it because its height will be set to 0pt thanks to the method above, everything else stays unaltered.
Please note that indexPathOfCellYouWantToHide can be changed at anytime :)
In > Swift 2.2, I've combined few answers here.
Make an outlet from storyboard to link to your staticCell.
#IBOutlet weak var updateStaticCell: UITableViewCell!
override func viewDidLoad() {
...
updateStaticCell.hidden = true
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row == 0 {
return 0
} else {
return super.tableView(tableView, heightForRowAtIndexPath: indexPath)
}
}
I want to hide my first cell so I set the height to 0 as described above.
In addition to #Saleh Masum solution:
If you get auto-layout errors, you can just remove the constraints from the tableViewCell.contentView
Swift 3:
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let tableViewCell = super.tableView(tableView, cellForRowAt: indexPath)
if tableViewCell.isHidden == true
{
tableViewCell.contentView.removeConstraints(tableViewCell.contentView.constraints)
return 0
}
else{
return super.tableView(tableView, heightForRowAt: indexPath)
}
}
This solution depends on the flow of your app. If you want to show/hide the cell in the same view controller instance this may not be the best choice, because it removes the constraints.
Swift 4:
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
var height = super.tableView(tableView, heightForRowAt: indexPath)
if (indexPath.row == HIDDENROW) {
height = 0.0
}
return height
}
For the easiest scenario when you hide cells at the very bottom of table view, you could adjust tableView's contentInset after you hide cell:
- (void)adjustBottomInsetForHiddenSections:(NSInteger)numberOfHiddenSections
{
CGFloat bottomInset = numberOfHiddenSections * 44.0; // or any other 'magic number
self.tableView.contentInset = UIEdgeInsetsMake(self.tableView.contentInset.top, self.tableView.contentInset.left, -bottomInset, self.tableView.contentInset.right);
}
This is new way to do this using https://github.com/k06a/ABStaticTableViewController
NSIndexPath *ip = [NSIndexPath indexPathForRow:1 section:1];
[self deleteRowsAtIndexPaths:#[ip] withRowAnimation:UITableViewRowAnimationFade]
Solution from k06a (https://github.com/k06a/ABStaticTableViewController) is better because it hides whole section including cells headers and footers, where this solution (https://github.com/peterpaulis/StaticDataTableViewController) hides everything except footer.
EDIT
I just found solution if you want to hide footer in StaticDataTableViewController. This is what you need to copy in StaticTableViewController.m file:
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
if ([tableView.dataSource tableView:tableView numberOfRowsInSection:section] == 0) {
return nil;
} else {
return [super tableView:tableView titleForFooterInSection:section];
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
CGFloat height = [super tableView:tableView heightForFooterInSection:section];
if (self.originalTable == nil) {
return height;
}
if (!self.hideSectionsWithHiddenRows) {
return height;
}
OriginalSection * os = self.originalTable.sections[section];
if ([os numberOfVissibleRows] == 0) {
//return 0;
return CGFLOAT_MIN;
} else {
return height;
}
//return 0;
return CGFLOAT_MIN;
}
Surely you can. First, return to your tableView number of cells you want to show then call super to achieve certain cell from your storyboard and return it for tableView:
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.mode.numberOfCells()
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAtIndexPath: self.mode.indexPathForIndexPath(indexPath))
return cell
}
If your cells has different hieght return it too:
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return super.tableView(tableView, heightForRowAtIndexPath: self.mode.indexPathForIndexPath(indexPath))
}
I got a better way to hide static cells and even sections dynamically without any hacks.
Setting the row height to 0 can hide a row, but that doesn't work if you want to hide an entire section which will hold some spaces even you hide all the rows.
My approach is to build a section array of static cells. Then the table view contents will be driven by the section array.
Here is some sample code:
var tableSections = [[UITableViewCell]]()
private func configTableSections() {
// seciton A
tableSections.append([self.cell1InSectionA, self.cell2InSectionA])
// section B
if shouldShowSectionB {
tableSections.append([self.cell1InSectionB, self.cell2InSectionB])
}
// section C
if shouldShowCell1InSectionC {
tableSections.append([self.cell1InSectionC, self.cell2InSectionC, self.cell3InSectionC])
} else {
tableSections.append([self.cell2InSectionC, self.cell3InSectionC])
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return tableSections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableSections[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return tableSections[indexPath.section][indexPath.row]
}
This way, you can put all of your configuration code together without having to write the nasty code to calculate number of rows and sections. And of course, no 0 heights anymore.
This code is also very easy maintain. For example, if you want to add/remove more cells or sections.
Similarly, you can create a section header title array and section footer title array to config your section titles dynamically.

How can I loop through UITableView's cells?

I have n sections (known amount) and X rows in each section (unknown amount. Each row has a UITextField. When the user taps the "Done" button I want to iterate through each cell and do some conditional tests with the UITextField. If the tests pass data from each cell is written to a database. If not, then a UIAlert is shown. What is the best way to loop through the rows and if there is a more elegant solution to this please do advise.
If you only want to iterate through the visible cells, then use
NSArray *cells = [tableView visibleCells];
If you want all cells of the table view, then use this:
NSMutableArray *cells = [[NSMutableArray alloc] init];
for (NSInteger j = 0; j < [tableView numberOfSections]; ++j)
{
for (NSInteger i = 0; i < [tableView numberOfRowsInSection:j]; ++i)
{
[cells addObject:[tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:j]]];
}
}
Now you can iterate through all cells:
(CustomTableViewCell is a class, which contains the property textField of the type UITextField)
for (CustomTableViewCell *cell in cells)
{
UITextField *textField = [cell textField];
NSLog(#"%#"; [textField text]);
}
Here is a nice swift implementation that works for me.
func animateCells() {
for cell in tableView.visibleCells() as! [UITableViewCell] {
//do someting with the cell here.
}
}
Accepted answer in swift for people who do not know ObjC (like me).
for section in 0 ..< sectionCount {
let rowCount = tableView.numberOfRowsInSection(section)
var list = [TableViewCell]()
for row in 0 ..< rowCount {
let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: row, inSection: section)) as! YourCell
list.append(cell)
}
}
for xcode 9 use this - (similar to #2ank3th but the code is changed for swift 4):
let totalSection = tableView.numberOfSections
for section in 0..<totalSection
{
print("section \(section)")
let totalRows = tableView.numberOfRows(inSection: section)
for row in 0..<totalRows
{
print("row \(row)")
let cell = tableView.cellForRow(at: IndexPath(row: row, section: section))
if let label = cell?.viewWithTag(2) as? UILabel
{
label.text = "Section = \(section), Row = \(row)"
}
}
}
for (UIView *view in TableView.subviews) {
for (tableviewCell *cell in view.subviews) {
//do
}
}
Since iOS may recycle tableView cells which are off-screen, you have to handle tableView one cell at a time:
NSIndexPath *indexPath;
CustomTableViewCell *cell;
NSInteger sectionCount = [tableView numberOfSections];
for (NSInteger section = 0; section < sectionCount; section++) {
NSInteger rowCount = [tableView numberOfRowsInSection:section];
for (NSInteger row = 0; row < rowCount; row++) {
indexPath = [NSIndexPath indexPathForRow:row inSection:section];
cell = [tableView cellForRowAtIndexPath:indexPath];
NSLog(#"Section %# row %#: %#", #(section), #(row), cell.textField.text);
}
}
You can collect an NSArray of all cells beforehands ONLY, when the whole list is visible. In such case, use [tableView visibleCells] to be safe.
quick and dirty:
for (UIView *view in self.tableView.subviews){
for (id subview in view.subviews){
if ([subview isKindOfClass:[UITableViewCell class]]){
UITableViewCell *cell = subview;
// do something with your cell
}
}
}
Here's a completely different way of thinking about looping through UITableView rows...here's an example of changing the text that might populate your UITextView by looping through your array, essentially meaning your tableView cell data.
All cells are populated with data from some kind of model. A very common model would be using an NSObject and NSMutableArray of those objects. If you were in didSelectRowAtIndexPath, you would then want to do something like this to affect the row you're selecting after modifying the array above:
for(YourObject *cellRow in yourArray)
{
if(![cellRow.someString isEqualToString:#""])
{
cellRow.someString = #"";
}
//...tons of options for conditions related to your data
}
YourObject *obj = [yourArray objectAtIndex:indexPath.row];
obj.someString = #"selected";
[yourArray insertObject:views atIndex:indexPath.row];
[yourArray removeObjectAtIndex:indexPath.row];
[yourTable reloadData];
This code would remove all the UITextField's text in every row except the one you selected, leaving the text "selected" in the tapped cell's UITextField as long as you're using obj.someString to populate the field's text in cellForRowAtIndexPath or willDisplayRowAtIndexPath using YourObject and yourArray.
This type of "looping" doesn't require any conditions of visible cells vs non visible cells. If you have multiple sections populated by an array of dictionaries, you could use the same logic by using a condition on a key value. Maybe you want to toggle a cells imageView, you could change the string representing the image name. Tons of options to loop through the data in your tableView without using any delegated UITableView properties.
swift 5:
guard let cells = self.creditCardTableView.visibleCells as? [CreditCardLoanCell] else {
return
}
cells.forEach { cell in
cell.delegate = self
}
I would like to add my two cents to the matter even though this post is old. I created an array of type UITableViewCell and appended each new cell to it before returning it in cellForRowAt. See code below:
var cellArray = [UITableViewCell]()
//UITableView code
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! Cell
//set up cell information
cellArray.append(cell)
return cell
}
Then if you need any information from each cell (i.e., UITextFields) in your Done button, you can iterate through the array like so in the desired context:
for cell in cellArray {
let myCell = cell as! Cell
//do stuff
}
Hope this helps anyone in the future

Resources