UITableViewCell randomly disappears + scrolling performance issue on iPhone 4 - iphone

To sum it up, I'm facing 2 problems, the 1st is that time to time some cells disappear from the tableview and reappear randomly. The 2nd is a scrolling performance issue on iPhone 4 and below.
1st problem :
I am displaying a simple list of elements in an UITableView by adding a subview the [cell contentView]. Most of the time it works well, but sometimes when i scroll (and really randomly) a cell disappears.
Because this cell which "disappeared" is reused, the reused cell will also be "blank" when I scroll. And randomly again a cell can reappear/disappear while scrolling.
Here is my code for the cellForRowAtIndexPath: method :
- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:CellIdentifier];
LBSelectorChampionViewController *item = [self itemAtIndexPath:indexPath];
if (cell == nil) {
NSLog(#"CELL NIL");
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
[[item view] setTag:99];
[[item champName] setTag:50];
[[item champImage] setTag:51];
[[item buttonFavorite] setTag:52];
[[cell contentView] addSubview:[item view]];
}
UILabel *championLabel = (UILabel*)[[[cell contentView] viewWithTag:99] viewWithTag:50];
LBFavoriteChampionButton *buttonFavorite = (LBFavoriteChampionButton*)[[[cell contentView] viewWithTag:99] viewWithTag:52];
UIImageView *championImage = (UIImageView*)[[[cell contentView] viewWithTag:99] viewWithTag:51];
// Text
[championLabel setText:[item displayValue]];
[championImage setImageWithURL:[NSURL URLWithString:[item imageUrl]]];
// Fav button
[buttonFavorite setCurrentChampion:item];
if ([[self favoritesChampions] containsObject:item]) {
[buttonFavorite setSelected:YES];
[buttonFavorite setIsFavorite:YES];
} else {
[buttonFavorite setSelected:NO];
[buttonFavorite setIsFavorite:NO];
}
return cell;}
}
I've tried to log everything, I checked if "item" could be sometimes null and it's never the case. But when a cell disappears, the [[[cell contentView] subviews] count] is equal to 0, which normally should be 1.
I really don't understand what's happening here. I tested it on real devices + simulator and it happens with both of them.
2nt problem :
My other "problem" is that the scrolling of the tableview is not as smooth as i would expect it to be on the iPhone 4 (tested on iOS 6 and iOS 7, same result :-( ). I'm using SDWebImage to load images asynchronously and to cache them, I'm reusing cells, what could I do to improve the performances ? I tested on an iPhone 4S and had no problem, scrolling is very smooth.
Am I doing something wrong ? Any ideas about one of my problem ?
Thank you for taking the time to answer me.
EDIT : 1st attempt to solve the problem
Trying to customize cell with a custom UITableViewCell subclass :
- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"LBListChampionCell";
LBListChampionCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil){
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"LBListChampionCell" owner:self options:nil];
cell = [topLevelObjects objectAtIndex:0];
}
LBSelectorChampionViewController *item = [self itemAtIndexPath:indexPath];
[[cell championName] setText:[item displayValue]];
[[cell championLogo] setImageWithURL:[NSURL URLWithString:[item imageUrl]]];
return cell;
}
I wasn't able for the moment to reproduce the "disappear" bug (sometimes it takes a moment to reproduce it...), but there is no improvement at all concerning the performances :(. Even while just setting a dummy text : [[cell championName] setText:#"Test"]; (and commenting the item part) the scrolling is still not really smooth.
Any ideas ?
EDIT 2 : Best solution (thanks to rdelmar)
Create a subclass of UITableViewCell and load the nib in viewDidLoad :
- (void)viewDidLoad
{
...
UINib *nib = [UINib nibWithNibName:#"LBListChampionCell" bundle:nil];
[[self tableView] registerNib:nib forCellReuseIdentifier:#"LBListChampionCell"];
}
- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
LBListChampionCell *cell = [tableView dequeueReusableCellWithIdentifier:#"LBListChampionCell"];
LBSelectorChampionViewController *item = [self itemAtIndexPath:indexPath];
[[cell championName] setText:[item displayValue]];
[[cell championLogo] setImageWithURL:[NSURL URLWithString:[item imageUrl]]];
...
}
It increased the scrolling performance (still not perfectly smooth on iPhone 4 but it works well). Moreover it seems that no cell are disappearing anymore :-)
Thanks rdelmar!

I think somehow LBSelectorChampionViewController *item = [self itemAtIndexPath:indexPath]; from one of your cell's contentView was added to another cell's contentView, which would cause the previous cell's contentView to have 0 subview.

I think you are getting the first problem because of cell reusability. LBSelectorChampionViewController *item = [self itemAtIndexPath:indexPath]; will not always be added to the [cell contentView] as cell may not be nil. In addition, there might be a situation when this view will be added to another cell and removed from the previous. Anyway, this will be easier to fix if you subclass UITableViewCell and make LBSelectorChampionViewController part of this custom cell. This will make everything easier and you will never meet reusability problems.
I am not exactly familiar with SDWebImage, but maybe the problem is that it doesn't cache images and tries to load new image every time [championImage setImageWithURL:[NSURL URLWithString:[item imageUrl]]]; is hit. I've used AFNetworking in a few projects to load images and have never had any problems with it.
Hope this is helpful!
Cheers!

Related

Scroll list of thumbnails

I need to allow my users to scroll through a list of thumbnails in the documents directory on an iPad application. When they tap on one of the thumbnails, I need to know which one was tapped (or have it call a method, which is basically the same thing.)
I know how to put the thumbnails in the documents directory, and how to read them from there. But I’m not sure which widget is best for displaying the content. Is it UITableView? CCScrollLayer? CCMenuAdvanced? Something else?
CCScrollLayer doesn't work as well as UIScrollView.
I use the view to CCdirector for add UIkit.
UIScrollView *scrollView = [UIScrollView alloc] init];
[[[CCDirector sharedDirector] view] addSubview:scrollView];
or add UITableView.
Take all the paths for thumbnails in one array, lets call pathsArray
NSArray *pathsArray = [seld getPathsForAllImages];
Now implement UITableViewDataSource and UITableViewDelegate:
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [pathsArray count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
NSString *pathForImage = [pathsArray objectAtIndex:indexPath.row];
cell.imageView.image = [UIImage imageWithContentsOfFile:pathForImage];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *pathForImage = [pathsArray objectAtIndex:indexPath.row];
}
I've had all kinds of problems with overlaying a UIScrollView on a cocos2d project. Even with all the suggested hacks, if a single frame takes too long in cocos2d, the UIScrollView just stops working right. I would suspect that would happen with a UITableView as well.
To solve my own problems, I created a custom ScrollNode class. It's really easy to use:
// create the scroll node
ScrollNode *scrollNode = [ScrollNode nodeWithSize:CGSizeMake(size.width, size.height)];
[self addChild:scrollNode];
// Generate some content for the scroll view
// add it directly to scrollView, or to the built in menu (scrollView.menu)
[scrollNode.menu addChild:yourMenuItem];
// Set the content rect to represent the scroll area
CGRect contentRect = [scrollNode calculateScrollViewContentRect];
[scrollNode setScrollViewContentRect:contentRect];

What is wrong with my UITableView cellForRowAtIndex for Single Selection?

Below is code for UITableView, But when i scroll its behaves weirdly (too annoying)... This problem is due to reuseIdentifier.... but dont know how to solve..
- (UITableViewCell *)tableView:(UITableView *)tableView1 cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView1 dequeueReusableCellWithIdentifier:CellIdentifier];
NSInteger imgTag = 1;
NSInteger lblTag = 2;
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(2, 2, 52, 52)];
// Image:[UIImage imageNamed:[self.glassType objectAtIndex:indexPath.row]]];
imgView.tag = imgTag;
[cell.contentView addSubview:imgView];
[imgView release];
UILabel *lblName = [[UILabel alloc] initWithFrame:CGRectMake(60, cell.frame.size.height/4, 200, 21)];
// lblName.text = [self.glassName objectAtIndex:indexPath.row];
lblName.tag = lblTag;
[cell addSubview:lblName];
[lblName release];
}
NSInteger imgIndex = 2;
NSInteger lblIndex = 3;
((UIImageView *)[cell viewWithTag:imgTag]).image = [[self.glassType objectAtIndex:indexPath.row] objectAtIndex:imgIndex];
((UILabel *)[cell viewWithTag:lblTag]).text = [[self.glassName objectAtIndex:indexPath.row] objectAtIndex:lblIndex];
return cell;
}
- (void)tableView:(UITableView *)tableView1 didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView1 cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
How to make Cell for row at index so that it remains constant even when scrolled??? Also how to make single selection in UITableView??
The answer is that you should not add subviews to your table cells outside of the "if (cell == nil) { ..." clause or they get added over and over again to the same cell when it gets re-used.
See my answer to this question for a more detailed explanation, including code for how to fix it:
cellForRowAtIndexPath memory management
You also cannot store state in table cells because as soon as they scroll offscreen they are recycled and re-appear at a different index in your table. You need to set up an array of model objects to store state for your table cells (such as what their accessory type should be). A more detailed explanation can be found in my answer to this question:
Looping through UITableViewCells of a UITableView
If you fix how you are adding subviews to the cells, and store your "ticked" state in an array of model objects as well as setting the cell.accessoryType (so that it can be restored when the cell is dequeued), then your approach to row selection is otherwise correct.
So put this in your tableView:cellForRowAtIndexPath: method, just before the return cell;:
MyModelObject *object = [self.arrayOfModelObjects objectAtIndex:indexPath.row];
BOOL isChecked = object.checked;
cell.accessoryType = isChecked? UITableViewCellAccessoryCheckmark: UITableViewCellAccessoryNone;
And in your tableView: didSelectRowAtIndexPath: method, get rid of the current logic and replace it with:
- (void)tableView:(UITableView *)tableView1 didSelectRowAtIndexPath:(NSIndexPath *)indexPath
for (int i = 0; i < [self.arrayOfModelObjects count]; i++)
{
MyModelObject *object = [self.arrayOfModelObjects objectAtIndex:i];
object.checked = (i == indexPath.row); // only check the one we just tapped
}
//refresh table to update the accessory views for all rows
[tableView1 reloadData];
}
Obviously replace the arrayOfModelObjects with your own model implementation. You could just use an array of NSNumber objects containing bools if you don't want to create a custom class for this purpose.
The recycling queue is like a pool where previously created Cells are stored before to reuse them. For example when you scrolls up, at the moment the cell disappears above, it is stored in the queue and becomes available for the cell that will appear at the bottom. Ok ?
Actually the number of cells really created is exactly the max simultaneous cell you can display in your table (in most cases from 3 to 8). In other words your if (cell == nil) code is executed (more or less from 3 to 8 times) at the first reloadData to create the pool of cells your table needs.
Then all you make on a cell is kept as it and appears again when you dequeue it. It's now easy to understand that, in your code, you have to make all strictly row-dependant settings outside the if (cell == nil) block. The same way, do not add subViews outside the if (cell == nil) block, you can imagine the thousands of subview you will add each time you reset a dequeued cell !
Tip: if you need some custom cleanup before reusing a cell (like to set an image to blank), you can create a custom UITableviewCell class and implements the prepareForReuse method.
Is it clear ?
Always reload your tableView in viewWillAppear method instead of viewDidLoad.
(void) viewWillAppear:(BOOL)animated{
[self.tableView reloadData];
}
This avoids most of all unexpected and annoying problems. :)

Programmatically scrolling to and coloring a UITableViewCell at runtime

I have UITableViewController which contains a list of items. Now, I want the list to be automatically scrolled to a item (index = bestOne ) once the view appears. Meanwhile I want the item to be colored into red and be labeled as Marked.
My code roughly achieves what I want. But, I actually see more than one red items iterating: every 10 items, there is a red item.
I am quite new to iphone development, I figure it might have something to do with reusable cells. But I am not exactly sure why. Can anybody suggest one way to solve this issue? Thanks in advance.
(void)viewDidAppear:(BOOL)animated
{
if (self.bestOne != -1)
{
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.bestOne inSection:0];
[self.tableView scrollToRowAtIndexPath: atScrollPosition: animated:YES];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [self.array objectAtIndex:indexPath.row];
if (indexPath.row == self.bestOne)
{
cell.detailTextLabel.text = #"Marked";
cell.textLabel.textColor = [UIColor redColor];
}
return cell;
}
You are right about the reusable cells part.
Your code should be something like –
cell.textLabel.text = [self.array objectAtIndex:indexPath.row];
if (indexPath.row == self.bestOne)
{
cell.detailTextLabel.text = #"Marked";
cell.textLabel.textColor = [UIColor redColor];
}
else
{
cell.detailTextLabel.text = #"";
}
On reuse, you get the exact cell that you had set before. While other cells are undistinguishable, the marked cell stands out with its specifically set detailTextLabel. You need to reset it before you can use it as an unmarked cell.
you look like you are on the right track with the color issue, you may accumulate red colored text cells, if you aren't calling [tableView reloadData] or reloading the old red cells specifically, which you would want to do if you have a large table. your scrolling looks good, don't know why that wouldn't work.

iphone Scrolling of tableview with custom cells is too slow

I have this problem when deploying my application on iphone, which wasn't detected on the simulator.
this the code of the cellforrow...
- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"beginning cellforRowAtIndexPath for section %d, and cell %d",[indexPath indexAtPosition:0],[indexPath indexAtPosition:1]);
static NSString *MyIdentifier = #"MyIdentifier";
NSString *fieldTitle;
NSString*fieldDescription;
[_stopWatch start];
[PersonalSection GetField:&fieldTitle AndValue:&fieldDescription UsingIndexPath:indexPath AndPersonalInformation:_personalInfo];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:#"ViewContent" owner:self options:nil];
cell = tvCell;
self.tvCell=nil;
((UILabel*) [cell.contentView viewWithTag:1]).layer.cornerRadius=11;
((UILabel*) [cell.contentView viewWithTag:2]).layer.cornerRadius=11;
}
UILabel*mainLabel=(UILabel*) [cell.contentView viewWithTag:1];
mainLabel.text=fieldTitle;
//mainLabel.textColor = [UIColor colorWithRed:0.745 green:0.116 blue:0.176 alpha:1.0];
UILabel*detailLabel=(UILabel*)[cell.contentView viewWithTag:2];
detailLabel.text=fieldDescription;
[_stopWatch stop];
NSLog(#"---------End cellforRowAtIndexPath");
return cell;
}
the rest is for sections and it's like return 3 or 5 no real bottleneck there.
so i'm wondering what's slowing it so much.
now the data fetching "[PersonalSection GetField:&fieldTitle..." is rather fast, it takes on the iphone maximum 0.1 ms. The problem is somewhere else, i'm guessing there's a way for optimizing this code, and i'm wondering about the custom cell influence it's only a cell with label and textfield linked to this ViewController.
Any ideas.
When you create the cell you're setting the identifier to #"cell" but when you dequeue it you're looking for #"MyIdentifier". It looks like you're recreating the cell every time though this.
Ok, the main performance issue was rounding the corners of the subviews of the contentview.
using QuartzCore:
#import <QuartzCore/QuartzCore.h>
((UILabel*) [cell.contentView viewWithTag:1]).layer.cornerRadius=11;
I removed those and decreased the sizes of the controls to fit inside the cell of a sectioned table. and now they look round but the textfield and label are not.
this has fixed my scrolling performance noticeably.
Thank you all for your help.

UITextField inside of UITableViewCell will not activate on iPad but works on iPhone

I have a UITextField inside a UITableViewCell. It will not activate on the iPad (but it works fine on the iPhone) no matter what I try. Tapping on it and telling it to become the firstResponder both fail. The odd thing is that if I take the exact same code and move it to another view controller in my app it executes just fine. This makes it seem as if there is likely a problem in the parent UITableViewController but I can't find anything obvious. I'm hoping that someone out there has experienced a similar problem and can point me in the right direction.
Below is the sample code that works fine when I move it to a new project or put it in a new view controller launched immediately by my app delegate:
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
if (indexPath.row == 0) {
UITextField *nameText = [[UITextField alloc] initWithFrame:CGRectMake(5, 5, cell.contentView.frame.size.width, cell.contentView.frame.size.height)];
nameText.delegate = self;
nameText.backgroundColor = [UIColor redColor];
[cell.contentView addSubview:nameText];
[nameText becomeFirstResponder];
[nameText release];
}
// Configure the cell...
return cell;
}
Help!
As is typical for me if I just ask the question I find the answer a few moments later. It turns out I did have a view several steps before that had asked for the first responder but not resigned it. Live and learn!