Reputation: 4728
In my app I have a table view and 4 images view in one row. When I scroll the table view then cell for row at index path method is again called and then the app crashes. How can I prevent table view reloading when scrolling. My part of code is :-
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = nil;
static NSString *AutoCompleteRowIdentifier = @"AutoCompleteRowIdentifier";
cell = [tableView dequeueReusableCellWithIdentifier:AutoCompleteRowIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:AutoCompleteRowIdentifier] autorelease];
for (int i=0; i <= [wordsInSentence count]; ++i) {
UIImageView *imageView1 = [[[UIImageView alloc] initWithFrame:CGRectMake(30+90*(i%4), 15, 80, 100)] autorelease] ;
imageView1.tag = i+1;
[imageViewArray insertObject:imageView1 atIndex:i];
[cell.contentView addSubview:imageView1];
}
}
int photosInRow;
if ( (indexPath.row < [tableView numberOfRowsInSection:indexPath.section] - 1) || ([wordsInSentence count] % 4 == 0) ) {
photosInRow = 4;
} else {
photosInRow = [wordsInSentence count] % 4;
}
for ( int i = 1; i <=photosInRow ; i++ ){
imageView = (UIImageView *)[cell.contentView viewWithTag:j];
[self showImage:imageView];
}
return cell;
}
Please help. Any help will be appreciated.
Thanks, Christy
Upvotes: 0
Views: 5568
Reputation: 44633
The only problem I see is this,
for ( int i = 1; i <= photosInRow ; i++ ){
imageView = (UIImageView *)[cell.contentView viewWithTag:j];
[self showImage:imageView];
}
What is j
here? I suggest you change that to i
i.e.
for ( int i = 1; i <=photosInRow ; i++ ){
imageView = (UIImageView *)[cell.contentView viewWithTag:i];
[self showImage:imageView];
}
As such only other flaw I see is the logic here,
for (int i=0; i <= [wordsInSentence count]; ++i) {
UIImageView *imageView1 = [[[UIImageView alloc] initWithFrame:CGRectMake(30+90*(i%4), 15, 80, 100)] autorelease] ;
imageView1.tag = i+1;
[imageViewArray insertObject:imageView1 atIndex:i];
[cell.contentView addSubview:imageView1];
}
You only need to add 4 image views in a row. Not the the total number of image views in each row. This is flawed logic. Suggested update to
for (int i = 0; i < 4; ++i) {
UIImageView *imageView1 = [[[UIImageView alloc] initWithFrame:CGRectMake(30+90*(i%4), 15, 80, 100)] autorelease] ;
imageView1.tag = i+1;
int trueImageIndex = indexPath.row * 4 + i;
[imageViewArray insertObject:imageView1 atIndex:trueImageIndex];
[cell.contentView addSubview:imageView1];
}
Upvotes: 1