Use uicollectionview inside uitableviewcell - ios

I can't solve next problem.
I want to display 20 table cells, each contains a unique UICollectionView.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *package=[_packageList objectAtIndex:indexPath.row];
static NSString *CellIdentifier = #"package";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UICollectionView *cellImageCollection=(UICollectionView *)[cell viewWithTag:9];
cellImageCollection.restorationIdentifier=[NSString stringWithFormat:#"%li", (long)indexPath.row, nil];
cellTracking.text=[NSString stringWithFormat:#"Row #%li",(long)indexPath.row];
return cell;
}
-(NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
int row=[collectionView.restorationIdentifier intValue];
return [[[_packages objectAtIndex:row] valueForKey:#"imageGallery"] count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
int row=[collectionView.restorationIdentifier intValue];
NSString *imgStrLink=[[[_packages objectAtIndex:row] valueForKey:#"imageGallery"] objectAtIndex:indexPath.row];
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"ImageID" forIndexPath:indexPath];
UIImageView *imageView=(UIImageView *)[cell viewWithTag:2];
imageView.image=....;
return cell;
}
Function tableView:cellForRowAtIndexPath: is called 20 times, but collectionView:numberOfItemsInSection: and collectionView:cellForItemAtIndexPath: only 4 times.
As seen in the screenshots UICollectionView is repeated every fourth line.
What is my fault?

I too faced this problem, the reason I got this problem was because both datasource and delegates for the tableview and collectionView were to the same parent viewcontroller.
It started working for me when I changed the datasource and delegate of the collectionView to another View say ParentView, and I added the collectionView to this ParentView and then finally added ParentView as conentView of the cell.
My previous answer which points to two nice tutorials was deleted by someone saying that I should include the essential parts of the content here(because the link may become invalid in future)...but I cannot do that as those are codes written by the tutorial owners and also the whole codes are essential too :), so now I am giving the link to the source code...
HorizontalCollectionViews
AFTabledCollectionView
-anoop

since Xcode 7 and iOS9 you can use UIStackView - best solution for design if collectionview or tableview are containing each other.

Related

IOS-TableView Cell: dequeueReusableCellWithIdentifier issue

In my project, I create everything by code, like tableviews and cells. I have function to add cells.
The situation is: I have 10 object in my array, when program runs, the function (- (TodoTableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath) runs through all 10 cells as I scroll, it does run 10 times of init... function in cell class. BUT, when I add a new cell in the program, then I found that this new cell never calls the init function for some reason. (The cell is being successfully created though... weird)
I use this part to add cell:
[self.tableView beginUpdates];
[self.todoItemList insertObject:newItem atIndex:toBeAddedIndex];
[self.tableView insertSections: [NSIndexSet indexSetWithIndex:toBeAddedIndex] withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates];
and in this function:
- (TodoTableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"Scroll to %ld", indexPath.section);
static NSString *cellIdentifier = #"TodoCell";
TodoTableViewCell *cell = (TodoTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
//If the current cell is dummycell, make it transparent
cell.todoItem = (TodoItem *)(self.todoItemList[indexPath.section]);
I don't know why, anyone please kindly help
----------UPDATE-----------------
NSString *cellIdentifier = [NSString stringWithFormat:#"TodoCell%ld",indexPath.section];
I found that if I change to this line. every time a add a new cell, it just calls the init function! but... if I do delete first and then add, problem still there, because this identifier has been created and used and stored I guess.
try to call:
[self.tableView insertRowsAtIndexPaths:<#(NSArray *)#> withRowAnimation:<#(UITableViewRowAnimation)#>]

UITableViewController customCell disappear and appear as they wish both on scroll and load

I have been looking for answers for more than 2 days now. It just does not seem to solve.
Here is the code for cell
- (myCustomCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
CustomData *m = (CustomData *)[self.allCustomData objectAtIndex:indexPath.row];
static NSString *CellIdentifier = #"customCell";
myCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
[cell setBackgroundColor:[UIColor colorWithRed:255.0f green:255.0f blue:255.0f alpha:1]];
[cell.customTitle setText:m.name];
[cell.customStatus setText:#"Download"];
NSLog(#"%#",cell.customTitle.text);
return cell;
}
'cell' never returns nil. the log always prints the correct text. But the cells appear empty for some reason. On load I notice the first cell appears empty, and then on scroll, randomly 2-3 cells of any order become empty. The first cell often appears back on scroll.
I can't seem to understand what the issue could be.
UPDATE
Here are two screen shots. First one is how the table loads, I have put a background color just for debugging purpose. As you see the first cell is not showing up.
The one below is the second screenshot where I changed the orientation and scrolled a bit. You see how the first cell magically appears and the second goes away.
Also for debugging purpose, I added these two methods.
- (void)tableView:(UITableView *)tableView willDisplayCell:(dtEditionCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
NSLog(#"Display %# %d %f",cell.editionTitle.text,indexPath.row,cell.frame.origin.x);
}
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(dtEditionCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
NSLog(#"End Display %# %d %f",cell.editionTitle.text,indexPath.row,cell.frame.origin.x);
}
The log prints as expected. All cells are visible with correct text.
I don't know if it has something to do, but the method you show is not exactly the one used by the tableview. Here is how I do it with custom cells. I'm doing it a lot and works fine:
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
TextCell *cell = [tableView dequeueReusableCellWithIdentifier:#"textCellId" forIndexPath:indexPath];
TextFieldContent *cellContent=[[self.dataSource objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
cell.titleLabel.text=cellContent.titleLabel;
cell.textField.placeholder=cellContent.placeHolder;
cell.textField.tag=cellContent.tag;
cell.textField.keyboardType=UIKeyboardTypeDecimalPad;
cell.textField.delegate=self;
return cell;
}
TextFieldContent is a cutom object that hold all the properties of the custom cell. For easier implementation.

xcode how to display images in collection view cell from database

I am just a beginner. i want to display image which is stored in database in a collection view cell. I have already created database and collection view. my code is as follow,
MyDatabase *data;
data=[MyDatabase new];
imagearray=[data OpenMyDatabase:#"SELECT pic_name FROM exterior" :#"pic_name"];
so my question is how can i display images ? let me know the way/code
thanks in advance
You can use following code for display UIImage grid. Add UICollectionView for your xib file. Don't forget to set the delegate in collection.
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return noOfItem/ noOfSection;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView
numberOfItemsInSection:(NSInteger)section
{
return noOfSection;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = #"Cell";
UICollectionViewCell *cell =
[collectionView dequeueReusableCellWithReuseIdentifier:identifier
forIndexPath:indexPath];
UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
recipeImageView.image = [imageArray objectAtIndex:
(indexPath.section * noOfSection + indexPath.row)];
return cell;
}
In your xib file add UIImageView to your CollectionViewCell and change it tag value to 100.
Please go through below links.
http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UICollectionView_class/Reference/Reference.html
Above link is from Apple developer site. It has all details of UIcollectionview and tutorials related it. Below URL is also having sample tutorial, which will help you a lot.
http://www.raywenderlich.com/22324/beginning-uicollectionview-in-ios-6-part-12
You have images array retrieved from database. Now it will act as data source for collection view. You need to form UICollectionViewCell which will have those images accordingly. Please study above links, you will get to know.

Error while adding UICollectionView inside UITableViewCell

So I am trying to display horizontally scrollable collection view inside tableviewcell. the code i am using is
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = (UITableViewCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UICollectionViewController *cv = [self.storyboard instantiateViewControllerWithIdentifier:#"collectionViewID"];
cv.view.frame = cell.contentView.bounds;
[self addChildViewController:cv];
[cell.contentView addSubview:cv.view];
[cv didMoveToParentViewController:self];
return cell;
}
I am getting error: Object can not be nil. I'd appreciate if someone can help me out understanding the error.
I have done this in my app.
I found it much easier to subclass UITableViewCell. The I could put all the UICollectionView setup and the UICollectionView datasource and delegate inside the code for the cell.
I then provided one public property of type NSArray which I pass into the cell. The cell then uses this array as the datasource for the UICollectionView that it owns itself.
Made it a lot easier to manage.
check your UICollectionViewControlle's attribute inspector for identifier value {collectionViewID}
EDIT
[self addChildViewController:cv]; --> I think you want to add cv to the cell, isn't you?

tableView: cellForRowAtIndexPath: get called not only for visible cells?

I have a tableView with sections, which could be opened and closed. So, when I tap on a section to open it, it is getting filled up with cells and -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *) get called exactly as much times as I provided in -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section.
Is that correct? Shouldn't it be just number of visible cells?
Because in my case I have bad situation: I have a lot of custom cells (50~100 cells) and calling -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *) for each cell slows down the opening of a section, cause each time reading from nib is performed and cell content is being populated with image.
I've check visibility of cell inside -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *) like this:
if ([[self.tableView indexPathsForVisibleRows] containsObject:indexPath])
NSLog(#"visible %#", indexPath);
and it shows that from out of 45 cells, only 6 or 7 are visible. Others are out of visible area. But creating cells still performed.
Here is the code:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"IVCell";
IVCamera *camera = [server.cameras objectAtIndex:indexPath.row];
IVServerListViewCell *cell = (IVServerListViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:#"IVServerListCell" owner:self options:nil];
cell = (IVServerListViewCell*)_tableViewCell;
self.tableViewCell = nil;
}
[cell textLabel].text = camera.cameraName;
cell.preview = camera.preview;
cell.userData = camera;
cell.isEnabled = (server.isInactive)?NO:camera.isOnline;
return cell;
}
Is it still correct? Or am I missing something?
increase your
estimatedRowHeight of UITableview.
Well, I somehow dealt with my problem. Here are my ideas and thoughts how I came to the solution. Maybe it could be helpful to somebody.
I've instructed memory allocations and call stack using Instruments during opening section events. It showed me, that the majority of time is spent on loading cell from nib file.
Firstly, that I've done was reducing the size of nib file, i.e. minimizing the number of views used in custom tableview cell (now its only 2 views and 2 labels, instead of 6 views, 2 images and 2 labels before). It gave me some improve in cells loading. Apple documentation suggests to use as few as possible views and do not use transparency. So be attentive to these suggestions.
Secondly, as I discovered earlier, that not all cell are visible which are created by -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *), I decided to reduce somehow the number of loadings new cells from nib file. To achieve this, I've came to simple idea: return blank default cells for invisible rows, while load custom cells from nib for visible ones. Here is the piece of code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self index:indexPath isInvisibleInTableView:tableView])
return [self getBlankCellForTableView:tableView];
// the rest of the method is the same
...
}
-(BOOL)index:(NSIndexPath*)indexPath isInvisibleInTableView:(UITableView*)tableView
{
NSMutableArray *visibleIndexPaths = [self getExtendedVisibleIndexPathsForTableView:tableView];
return ![visibleIndexPaths containsObject:indexPath];
}
-(UITableViewCell*)getBlankCellForTableView:(UITableView*)tableView
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"IVBlankCell"];
if (!cell)
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"IVBlankCell"] autorelease];
return cell;
}
As you can see, I'm not using just -(NSArray*)indexPathsForVisibleRows method of tableview for detecting visible cells. Instead, I've wrote my own method -(NSMutableArray*)getExtendedVisibleIndexPathsForTableView:(UITableView*)tableView. It was necessary because for some reason, when using -(NSArray*)indexPathsForVisibleRows the cells that are next to the last one visible cell or the cells that are previous to the first one visible cell were created as blank cells and looked like empty cells while scrolling. To overcome this, in -(NSMutableArray*)getExtendedVisibleIndexPathsForTableView: (UITableView*)tableView i'm adding border cells to the visible array cells:
-(NSMutableArray*)getExtendedVisibleIndexPathsForTableView:(UITableView*)tableView{
NSArray *visibleIPs = [tableView indexPathsForVisibleRows];
if (!visibleIPs || ![visibleIPs count])
return [NSMutableArray array];
NSIndexPath *firstVisibleIP = [visibleIPs objectAtIndex:0];
NSIndexPath *lastVisibleIP = [visibleIPs objectAtIndex:[visibleIPs count]-1];
NSIndexPath *prevIndex = ([firstVisibleIP row])?[NSIndexPath indexPathForRow:[firstVisibleIP row]-1 inSection:[firstVisibleIP section]]:nil;
NSIndexPath *nextIndex = [NSIndexPath indexPathForRow:[lastVisibleIP row]+1 inSection:[lastVisibleIP section]];
NSMutableArray *exVisibleIndexPaths = [NSMutableArray arrayWithArray:[tableView indexPathsForVisibleRows]];
if (prevIndex)
[exVisibleIndexPaths addObject:prevIndex];
[exVisibleIndexPaths addObject:nextIndex];
return exVisibleIndexPaths;
}
Thereby, I've reduced the time of opening sections with large number of custom cells, which was proved by Instruments tracing and felt while experiencing the app.
Simply add estimated height for UITableViewCell
Problem In my case was: cellforRowAtIndexPath was getting called array.count number of times, whereas, displayed cells where less than array.count.
To resolve this issue, I have just replaced,
(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
with,
(CGFloat)tableView:(UITableView )tableView estimatedHeightForRowAtIndexPath:(nonnull NSIndexPath )indexPath;
check your tableview size.
may be that your tableview height is very large that it keep loading cells until your cell fills all tableview size..
This seems correct yes. the idea about optimizing the loading itself lies within how "dequeueReusableCellWithIdentifier" works.
if u are loading the image from a remote location this is where u would want to optimize the code. but not from the loading of cells as this looks correct here.
I used some similar technique but since indexPathsForVisibleRows is sorted you don't need to use containsObject. Instead you can just do:
//
// Checks if indexPath is visible in current scroll state, we are expanding bounds by 1
// because the cells that are next to the last one visible or the cells that are previous
// to the first one visible could look empty while scrolling.
//
- (BOOL)isIndexPathVisible:(NSIndexPath *)indexPath
{
NSInteger row = [indexPath row];
NSArray *visible = [self.tableView indexPathsForVisibleRows];
NSInteger count = [visible count];
NSInteger first = (count > 0) ? MAX([visible[0] row] - 1, 0): 0;
NSInteger last = (count > 1) ? [visible[1] row] + 1: first + 2;
return row >= first && row <= last;
}
By the way; this assumes that you are using only one section. It won't work for more than one section.
Adding an else solved my problem.
Where I reseted any changes that were made to the cell.
if (! self.cell) {
self.cell = [[LanguageCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
self.cell.accessoryType = UITableViewCellAccessoryNone;
}
else
{
self.cell.checkImage.image = NO;
}

Resources