TableViewCell - Custom Cell iOS - Content - ios

i have a table with a custom cell. This cell have a label that i would like move in cell (if a condition is true). Why the position of label is updated only if the cellForRowAtIndexPath method for that cell is called for the second time?
This is the first question.
The second question is is as follows:
The custom cell contain a view, in this view i programmatically add images. If i have two sections in the table, after scrolling the table, the images of first cell in first section appear in the first cell of second section. Why?
This is the code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *idDettCal = #"cellaVotoCalciatore";
NSString *idRiepilogo = #"riepilogoCell";
NSString *idTotali = #"bonusTotaliCell";
//Dictionary per Titolari e Panchinari
NSDictionary *calciatore = [[NSDictionary alloc] init];
if (indexPath.section == 0 || indexPath.section == 1) {
foaVotoCalciatoreCell *cell = (foaVotoCalciatoreCell *)[tableView dequeueReusableCellWithIdentifier:idDettCal];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:idDettCal owner:self options:nil];
cell = [nib objectAtIndex:0];
}
//TITOLARI
if (indexPath.section == 0) {
calciatore = [titolari objectAtIndex:indexPath.row];
}
//PANCHINARI
else if (indexPath.section == 1) {
calciatore = [panchinari objectAtIndex:indexPath.row];
}
NSString *calciatoreStr =
[NSString stringWithFormat:#"%#%#%#%#",
[calciatore objectForKey:#"CALCIATORE"],
#" (",
[[calciatore objectForKey:#"SQUADRA"] substringToIndex:3],
#")"];
NSString *imgRuolo =
[NSString stringWithFormat:#"%#%#",
[calciatore objectForKey:#"RUOLO"],
#".jpg"];
cell.ruolo.image = [UIImage imageNamed:imgRuolo];
NSDictionary *dettaglioVoto = [[NSDictionary alloc] init];
UIImageView *imageIcona;
CGFloat offset;
dettaglioVoto = [calciatore objectForKey:#"VOTO_STM"];
offset = 0;
for (NSString *icona in dettaglioVoto) {
if ([icona isEqualToString: #"AMMONITO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"amm.png"]];
}
else if ([icona isEqualToString: #"GOL_FATTO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"golfatto.png"]];
}
else if ([icona isEqualToString: #"GOL_SUBITO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"golsubito.png"]];
}
else if ([icona isEqualToString: #"ENTRATO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"entrato.png"]];
}
else if ([icona isEqualToString: #"USCITO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"uscito.png"]];
}
else if ([icona isEqualToString: #"ESPULSO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"esp.png"]];
}
else if ([icona isEqualToString: #"ASSIST"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"assist.png"]];
}
else if ([icona isEqualToString: #"ASSIST_FERMO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"assistf.png"]];
}
else if ([icona isEqualToString: #"RIGORE_SEGNATO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"rigoresegnato.png"]];
}
else if ([icona isEqualToString: #"RIGORE_SBAGLIATO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"rigoresbagliato.png"]];
}
else if ([icona isEqualToString: #"RIGORE_PARATO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"rigoreparato.png"]];
}
else if ([icona isEqualToString: #"AUTOGOL"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"autogol.png"]];
}
else if ([icona isEqualToString: #"GOL_PARTITA"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"golvittoria.png"]];
}
else if ([icona isEqualToString: #"GOL_PAREGGIO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"golpareggio.png"]];
}
imageIcona.frame = CGRectMake(offset, 0, imageIcona.frame.size.width, imageIcona.frame.size.height);
offset = imageIcona.frame.size.width + offset + 2;
[cell.iconeDettaglio addSubview: imageIcona];
}
if (offset == 0) {
cell.calciatore.frame = CGRectMake(cell.calciatore.frame.origin.x, 14, cell.calciatore.frame.size.width, cell.calciatore.frame.size.height);
cell.iconeDettaglio.hidden = YES;
}
cell.calciatore.text = calciatoreStr;
cell.votoIniziale.text = [calciatore objectForKey:#"VOTO_PRNT"];
cell.votoFinale.text = [calciatore objectForKey:#"VOTO_PRNT_TOT"];
return cell;
}
//La giornata è calcolata. Sezione 2 = BONUS e TOTALI
else if (variabiliGlobali.gioCalcolata && indexPath.section == 2) {
NSDictionary *totaliVal;
NSDictionary *totaliTip;
totaliVal = [logCalValore objectAtIndex:indexPath.row];
totaliTip = [logCalTipo objectAtIndex:indexPath.row];
foaBonusTotaliCell *cell = (foaBonusTotaliCell *)[tableView dequeueReusableCellWithIdentifier:idTotali];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:idTotali owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.tipoBonusLabel.text = totaliTip;
cell.totaleLabel.text = totaliVal;
return cell;
}
else {
NSDictionary *riepilogoVal;
NSDictionary *riepilogoTip;
riepilogoVal = [logForValore objectAtIndex:indexPath.row];
riepilogoTip = [logForTipo objectAtIndex:indexPath.row];
foaRiepilogoCell *cell = (foaRiepilogoCell *)[tableView dequeueReusableCellWithIdentifier:idRiepilogo];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:idRiepilogo owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.voceRiepilogoLabel.text = riepilogoTip;
cell.valoreRiepilogoLabel.text = riepilogoVal;
return cell;
}
}
Thanks in advance.

First Question: Which label? What condition? Are you talking about this:
if (offset == 0) {
cell.calciatore.frame = CGRectMake(cell.calciatore.frame.origin.x, 14, cell.calciatore.frame.size.width, cell.calciatore.frame.size.height);
cell.iconeDettaglio.hidden = YES;
}
You have to be more specific here!
Second Question: The reason that wrong images show up in wrong cells is that your cells are being reused by the tableView. Make sure to set the custom cell's label.texts and imageView.images to nil right after dequeueReusableCellWithIdentifier: to ensure they are empty when reused.
WARNING: This is NOT a good idea:
[cell.iconeDettaglio addSubview: imageIcona];
Because your cell is being reused, and once reused, you'll see the previous imageIcona and add ANOTHER imageIcona on top as a subview. Make the imageIcona an IBOUTLET or property of your custom cell, and only set its image variable in cellForRowAtIndexPath:.

First question: I can't debug for you, but without running the code, i can imagine that this part of the code
if (offset == 0) {
cell.calciatore.frame = CGRectMake(cell.calciatore.frame.origin.x, 14, cell.calciatore.frame.size.width, cell.calciatore.frame.size.height);
cell.iconeDettaglio.hidden = YES;
}
is never reached the first time because of this other part of code
offset = imageIcona.frame.size.width + offset + 2;.
And after you scroll, this loop for (NSString *icona in dettaglioVoto) { is not performed because maybe dettaglioVoto is empty, and so the offset will remain equals to zero, and you will have it the way you want. But i can't be sure without you debugging your code to see why the if is not being reached the first time.
Second question: I don't think you are properly using the reuse mechanism for cells. So, if you are going to reuse the cells, you should use set prepareForReuse method in the cell code, like this:
-(void) prepareForReuse {
// Your code code here: like clearing old images and text and/or setting new images or text
}
Also, it normally works better if you register the nib for the table view, this way:
foaVotoCalciatoreCell *cell = (foaVotoCalciatoreCell *)[tableView dequeueReusableCellWithIdentifier:idDettCal];
if (cell == nil)
{
[[self tableView] registerNib:[UINib nibWithNibName:loadNibNamed:idDettCal bundle:nil]
forCellReuseIdentifier:nibWithNibName:loadNibNamed:idDettCal];
}

Related

After setting selectedBackgroundView of UITableViewCell when the cell is selected, background color of other components get changed

Due to some permission issue, in my tableView some cell can be selected by user and some cell can't be selected by that user. What I did in my cellForRowAtIndexPath is:
-(UITableViewCell *) tableView:(UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
int row = (int)[indexPath row];
static NSString *simpleTableIdentifier = #"EditProjectTableCell";
Project* project = (Project*)[self.projectList objectAtIndex:row];
EditProjectTableCell *cell = (EditProjectTableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:simpleTableIdentifier owner:self options:nil];
cell = [nib objectAtIndex:0];
cell.serial.layer.cornerRadius = 5;
cell.accessoryView = [[ UIImageView alloc ] initWithImage:[UIImage imageNamed:#"accessory_right.png"]];
cell.cellView.backgroundColor = [UIColor blackColor];
cell.backgroundColor = [UIColor blackColor];
}
if ([project.role isEqualToString:#"1"] || [project.role isEqualToString:#"2"]) {
UIView *customView = [[UIView alloc] initWithFrame:cell.frame];
customView.backgroundColor = [UIColor clearColor];
cell.selectedBackgroundView = customView;
}
else cell.selectionStyle = UITableViewCellSelectionStyleNone;
if(cell.imageFetchOperation != nil) [cell.imageFetchOperation cancel];
cell.imageFetchOperation = [[CellBlockOperation alloc] initWithIndexPath:indexPath
andPkId:project.pkId
andFetchImage:YES
andFetchReportCounter:NO
andFetchIssueCounter:NO
andFetchDrawingCounter:NO
andDelegate:self];
if(cell.counterFetchOperation != nil) [cell.counterFetchOperation cancel];
cell.counterFetchOperation = [[CellBlockOperation alloc] initWithIndexPath:indexPath
andPkId:project.pkId
andFetchImage:NO
andFetchReportCounter:YES
andFetchIssueCounter:NO
andFetchDrawingCounter:NO
andDelegate:self];
cell.projectName.text = project.name;
cell.projectNumber.text = project.number;
cell.owner.text = [NSString stringWithFormat:#"%# %#",project.ownerName,project.ownerLastName];
NSString* temp_date = [Utils stringFromDateForGUI:project.creationDate];
cell.date.text = temp_date;
[cell.syncStatusView setImage:[Utils getImageForSyncStatus:project.isDirty.intValue]];
NSNumber *ret = [self.reportCountList objectForKey:project.pkId];
if(ret == nil) {
cell.serial.text = #"";
[cell.counterFetchOperation setPkId:project.pkId];
[self.tableCellUpdateQueue addOperation:cell.counterFetchOperation];
} else {
cell.serial.text = [NSString stringWithFormat:#"%d",[ret intValue]];
}
id img = [self getSmallImage:project.pkId andIndexPath:indexPath andCell:cell];
if(img == nil || img == (id)[NSNull null]) {
img = [UIImage imageNamed:#"gray-img.jpg"];
cell.iconImageView.image = [UIImage imageNamed:#"project-icon.png"];
cell.iconImageView.hidden = NO;
} else {
cell.iconImageView.hidden = YES;
}
cell.imageView.image = (UIImage*)img;
if ([project.role isEqualToString:#"2"] || [project.role isEqualToString:#"1"])
cell.selectImageView.hidden = NO;
else
cell.selectImageView.hidden = YES;
return cell;
}
Selection part is working just fine. But if a cell is selected then the background color of a UILabel gets changed to clear color. See the below images for clear idea.
Before selection:
After Selection :

Populate UITableView via a string?

I have a simple iOS app which parses multiple JSON feeds and stores the data in multiple strings. I know exactly which strings to use for what and how long the count is because the JSON feeds are feeds that I control from some of my websites.
However, even though I have specified this in the "tableView cellForRowAtIndexPath" method, the UITableView still won't populate..
Is this because I am using strings to populate the UITableView? And if so, do you HAVE to use arrays to populate a UITableView.
Thanks for you're time :)
UPDATE: Here is m code:
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 5;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"Printing table view.");
static NSString *CellIdentifier = #"Cell";
AccountCell *cell = (AccountCell *)[account_table dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"AccountCell" owner:self options:nil];
cell = [nib objectAtIndex: 0];
// Draws the cell background.
cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"uiFeedletsnglass5.png"]];
// Draws the pressed cell background.
cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"cell-on.png"]];
// Round of edges of content view in Carousel.
cell.layer.cornerRadius = 5;
cell.layer.masksToBounds = YES;
cell.layer.borderWidth = 1.0f;
cell.layer.borderColor = [[UIColor grayColor] CGColor];
cell.profilepic.layer.cornerRadius = 5;
cell.profilepic.layer.masksToBounds = YES;
cell.profilepic.layer.borderWidth = 1.0f;
cell.profilepic.layer.borderColor = [[UIColor grayColor] CGColor];
}
if ((facebook_printed == 0) && (logged_facebook == 1)) {
NSString *full_name = [NSString stringWithFormat:#"%# %#", facebook_first_name, facebook_last_name];
cell.username.text = [NSString stringWithFormat:#"%#", full_name];
cell.account_type_name.text = [NSString stringWithFormat:#"Facebook"];
NSData *facebook_imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString: facebook_proffile_pic]];
UIImage *facebook_image = [[UIImage alloc] initWithData:facebook_imageData];
cell.profilepic.image = facebook_image;
facebook_printed = 1;
}
else if ((youtube_printed == 0) && (logged_youtube == 1)) {
cell.username.text = [NSString stringWithFormat:#"%#", youtube_profilename];
cell.account_type_name.text = [NSString stringWithFormat:#"YouTube"];
NSData *youtube_imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString: youtube_profilepic]];
UIImage *youtube_image = [[UIImage alloc] initWithData:youtube_imageData];
cell.profilepic.image = youtube_image;
youtube_printed = 1;
}
else if ((instagram_printed == 0) && (logged_instagram == 1)) {
cell.username.text = [NSString stringWithFormat:#"%#", instagram_name_tag];
cell.account_type_name.text = [NSString stringWithFormat:#"Instagram"];
NSData *instagram_imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString: instagram_profilepicture]];
UIImage *instagram_image = [[UIImage alloc] initWithData:instagram_imageData];
cell.profilepic.image = instagram_image;
instagram_printed = 1;
}
else if ((googleplus_printed == 0) && (logged_googleplus == 1)) {
cell.username.text = [NSString stringWithFormat:#"%#", googleplus_profilename];
cell.account_type_name.text = [NSString stringWithFormat:#"Google Plus"];
NSData *googleplus_imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString: googleplus_profilepic]];
UIImage *googleplus_image = [[UIImage alloc] initWithData:googleplus_imageData];
cell.profilepic.image = googleplus_image;
googleplus_printed = 1;
}
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
return cell;
}
Maybe try reloading the table view's data once you obtain the value of the string?
[tableView reloadData];
Right after much frustration and pretty much a lot of trial and error I finally figured out that it is because of if (cell == nil) that my Custom Cell was not loading (showing in the UITableView).
I was not aware of this at all, but from what I have read online it seems that when using UiTableViews in Storyboard UI's with Custom Cells, you are NOT meant to use the control statement if (cell == nil)
Thanks to everyone who commented on this post though. I appreciate you're help.

iPhone UITableView Scrolling and Searching Slow With Cell ImageView

My app is scrolling and Searching very slow when I have Images set for each cell.Pictures lifted faster, but still slow when searching. Here is my code in the cell at row. Any ideas?
#interface UIImage (TPAdditions)
- (UIImage*)imageScaledToSize:(CGSize)size;
#end
#implementation UIImage (TPAdditions)
- (UIImage*)imageScaledToSize:(CGSize)size {
UIGraphicsBeginImageContext(size);
[self drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
#end
cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
static NSInteger buton1_tag = 100;
static NSInteger buton2_tag = 101;
if (indexPath.section == 0) {
CellIdentifier = #"CellMuzikEkle";
}else{
if(indexPath.row == 0 && !self.editing)
CellIdentifier = #"CellPlayereEkle";
else
CellIdentifier = #"CellDizi";
}
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
if (indexPath.section == 1 && indexPath.row == 0 && !self.editing) // Grubu ekle
cell = [[[NSBundle mainBundle] loadNibNamed:#"Cell4" owner:self options:nil] objectAtIndex:0];
else{
if (indexPath.section == 0) {
cell = [[[NSBundle mainBundle] loadNibNamed:#"Cell" owner:self options:nil] objectAtIndex:5];
UIButton *ipodbuton = (UIButton *) [cell.contentView viewWithTag:buton1_tag];
[ipodbuton addTarget:self action:#selector(iPoddan_Ekle:) forControlEvents:UIControlEventTouchUpInside];
UIButton *yuklenenler = (UIButton *) [cell.contentView viewWithTag:buton2_tag];
[yuklenenler addTarget:self action:#selector(Yuklenenlerden_Ekle:) forControlEvents:UIControlEventTouchUpInside];
}else{
cell.textLabel.font = [UIFont boldSystemFontOfSize:15.0];
cell.textLabel.numberOfLines=2;
cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
[cell.imageView.layer setBorderWidth: 1.5];
}
}
}
if (indexPath.section == 1 && !self.editing && indexPath.row != 0)
cell.accessoryType =UITableViewCellAccessoryDetailDisclosureButton;
else
cell.accessoryType =UITableViewCellAccessoryNone;
if(indexPath.section == 0){
cell.textLabel.text = #"";
cell.detailTextLabel.text = #"";
cell.imageView.image = nil;
}else{
if (indexPath.row > 0 || self.editing) {
if (!self.editing)
indexPath = [NSIndexPath indexPathForRow:indexPath.row - 1 inSection:indexPath.section];
NSArray *aradizi = tableView == self.searchDisplayController.searchResultsTableView ? [[NSArray alloc] initWithArray:self.filteredListContent] : [[NSArray alloc] initWithArray:self.dizi];
if ([[NSUserDefaults standardUserDefaults] boolForKey:cellresimyuk_s])
cell.imageView.image = [[self Resim_Artwork:[aradizi objectAtIndex:indexPath.row]] imageScaledToSize:CGSizeMake(65, 50)];
else
cell.imageView.image = nil;
cell.textLabel.text = [[aradizi objectAtIndex:indexPath.row] objectForKey:isim_s];
NSTimeInterval theTimeInterval = [[[aradizi objectAtIndex:indexPath.row] objectForKey:sure_s] intValue] - 1;
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
NSDate *date1;
if (theTimeInterval >= 3600) {
[dateFormatter setDateFormat:#"HH:mm:ss"];
date1 = [dateFormatter dateFromString:#"00:00:00"];
}else{
[dateFormatter setDateFormat:#"mm:ss"];
date1 = [dateFormatter dateFromString:#"00:00"];
}
NSDate *date2 = [[NSDate alloc] initWithTimeInterval:theTimeInterval sinceDate:date1];
cell.detailTextLabel.text = [dateFormatter stringFromDate:date2];
}else{
if (tableView == self.searchDisplayController.searchResultsTableView)
cell.textLabel.text = AramaSonuclrPlayerEkle_lclz;
else
cell.textLabel.text = GrubuPlayereEkle_lclz;
}
}
return cell;
}
Resim_Artwork
- (UIImage *)Resim_Artwork:(NSDictionary *)dictr{
if ([dictr objectForKey:videoid_s]) {
if ([self Dosya_Varmi:[[rsm_favori stringByAppendingPathComponent:[dictr objectForKey:videoid_s]] stringByAppendingPathExtension:#"png"]])
return [UIImage imageWithContentsOfFile:[[rsm_favori stringByAppendingPathComponent:[dictr objectForKey:videoid_s]] stringByAppendingPathExtension:#"png"]];
}else{
if ([[[dictr objectForKey:urlsi_s] pathExtension] isEqualToString:#"mp4"]) {
AVURLAsset *assetresim = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:[kDocdir stringByAppendingPathComponent:[dictr objectForKey:urlsi_s]]] options:nil];
AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:assetresim];
gen.appliesPreferredTrackTransform = YES;
int suresi = CMTimeGetSeconds(assetresim.duration);
if (suresi > 0) {
CMTime time;
if (suresi>6)
time = CMTimeMakeWithSeconds(6.0, 600);
else
time = CMTimeMakeWithSeconds(0.0, 600);
NSError *error = nil;
CMTime actualTime;
CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
UIImage *thumb = [[UIImage alloc] initWithCGImage:image];
CGImageRelease(image);
return thumb;
}
}else {
if ([dictr objectForKey:kaynak_s]) {
AVAsset *asset = [AVURLAsset URLAssetWithURL:[NSURL URLWithString:[dictr objectForKey:urlsi_s]] options:nil];
for ( AVMetadataItem* item in [asset commonMetadata] ) {
if ([[item commonKey] isEqualToString:#"artwork"] )
if (item.dataValue != nil)
if ([UIImage imageWithData:item.dataValue])
return [UIImage imageWithData:item.dataValue];
}
}else{
if ([self Dosya_Varmi:[kDocdir stringByAppendingPathComponent:[dictr objectForKey:urlsi_s]]]){
AVAsset *asset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:[kDocdir stringByAppendingPathComponent:[dictr objectForKey:urlsi_s]]] options:nil];
for ( AVMetadataItem* item in [asset commonMetadata] ) {
if ([[item commonKey] isEqualToString:#"artwork"] )
if (item.dataValue != nil)
if ([UIImage imageWithData:item.dataValue])
return [UIImage imageWithData:item.dataValue];
}
}
}
}
}
return [self Resimm:#".varsayilan" Koordinat:CGRectMake(120,1320, 80, 60) retinami:0 grubu:6];
}
tableView willDisplayCell
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
NSArray *viewControllers = [self.tabBarController viewControllers];
NSArray *viewControllers2 = [[viewControllers objectAtIndex:0] viewControllers];
Player *detailViewController = (Player *)[viewControllers2 objectAtIndex:0];
[detailViewController.temalar Cell_Tema:cell];
cell.textLabel.backgroundColor = [UIColor clearColor];
cell.detailTextLabel.backgroundColor = [UIColor clearColor];
cell.textLabel.textColor = [detailViewController.temalar Baslik_Renk];
cell.detailTextLabel.textColor = [detailViewController.temalar Bilgi_Renk];
[cell.imageView.layer setBorderColor: [tableView.separatorColor CGColor]];
[((UIButton *) [cell.contentView viewWithTag:100]) setBackgroundImage:[self Resimm:#".buton" Koordinat:CGRectMake(0,1350, 94, 35) retinami:0 grubu:7] forState:UIControlStateNormal];
[((UIButton *) [cell.contentView viewWithTag:100]) setTitleColor:[detailViewController.temalar Baslik_Renk] forState:UIControlStateNormal];
[((UIButton *) [cell.contentView viewWithTag:101]) setBackgroundImage:[self Resimm:#".buton" Koordinat:CGRectMake(0,1350, 94, 35) retinami:0 grubu:7] forState:UIControlStateNormal];
[((UIButton *) [cell.contentView viewWithTag:101]) setTitleColor:[detailViewController.temalar Baslik_Renk] forState:UIControlStateNormal];
}
Here:
NSArray *aradizi = tableView == self.searchDisplayController.searchResultsTableView ?
[[NSArray alloc] initWithArray:self.filteredListContent] :
[[NSArray alloc] initWithArray:self.dizi];
You should avoid creating objects inside cellForRowAtIndexPath wherever possible.
Anyway you don't need to:
NSArray *aradizi = tableView == self.searchDisplayController.searchResultsTableView ?
self.filteredListContent :
self.dizi;
Here you seem to be creating and resizing thumbnails on the fly. :
if ([[NSUserDefaults standardUserDefaults] boolForKey:cellresimyuk_s])
cell.imageView.image = [[self Resim_Artwork:[aradizi objectAtIndex:indexPath.row]]
imageScaledToSize:CGSizeMake(65, 50)];
This is bound to jam up smooth tableView scolling. All of these should be pre-processed and cached, or at least only processed once here and cached for reuse.
Time-consuming nonUI processing like this can go onto another thread so that your scolling stays smooth even if the image isn't ready to show. Something like…
if ([[NSUserDefaults standardUserDefaults] boolForKey:cellresimyuk_s])
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImage* image =
[[self Resim_Artwork:[aradizi objectAtIndex:indexPath.row]]
imageScaledToSize:CGSizeMake(65, 50)];
dispatch_async(dispatch_get_main_queue(), ^{
//check our cell is still valid
if ([[self.tableView cellForRowAtIndexPath:indexPath] isEqual:cell]){
cell.imageView.image = image;
}
});
});
else
cell.imageView.image = nil;
Regarding the date formatter: these are heavyweight objects, you need to ensure to only create once, keep in a property for reuse. I suggest you do the following:
Declare two date formatter properties and another for your zero'd date. Initialise them all in viewDidLoad:
- (void)viewDidLoad {
[super viewDidLoad];
self.hoursFormat = [[NSDateFormatter alloc] init];
[self.hoursFormat setDateFormat:#"HH:mm:ss"];
self.minsFormat = [[NSDateFormatter alloc]init];
[self.minsFormat setDateFormat:#"mm:ss"];
self.zeroDate = [self.hoursFormat dateFromString:#"00:00:00"];
}
Then in cellForRowAtIndexPath:
NSDate* date = [self.zeroDate dateByAddingTimeInterval:theTimeInterval];
if (theTimeInterval >= 3600) {
self.label.text = [self.hoursFormat stringFromDate:date];
} else {
self.label.text = [self.minsFormat stringFromDate:date];
}
He Was, Thank you for the answer. performance was very nice. But since I made this change, the program closes.
new codes:
NSMutableArray *aradizi;
if (tableView == self.searchDisplayController.searchResultsTableView)
aradizi = self.filteredListContent;
if (indexPath.section == 2 && tableView != self.searchDisplayController.searchResultsTableView)
aradizi = self.dizi_klasorler;
if (indexPath.section == 3)
aradizi = self.dizi_veriler;
if ([[NSUserDefaults standardUserDefaults] boolForKey:cellresimyuk_s]){
if (cell.imageView.image == nil)
cell.imageView.image = [[self Resimm:#".varsayilan" Koordinat:CGRectMake(120,1320, 80, 60) retinami:0 grubu:6] Resim_Skala:CGSizeMake(60, 45)];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImage* image = [[self Resim_Artwork:[[aradizi objectAtIndex:indexPath.row] objectForKey:urlsi_s]] Resim_Skala:CGSizeMake(60, 45)];
dispatch_async(dispatch_get_main_queue(), ^{
//check our cell is still valid
if (tableView == self.searchDisplayController.searchResultsTableView){
if ([[self.searchDisplayController.searchResultsTableView cellForRowAtIndexPath:indexPath] isEqual:cell])
cell.imageView.image = image;
}else{
if ([[self.tableView cellForRowAtIndexPath:indexPath] isEqual:cell])
cell.imageView.image = image;
}
});
});
}else
cell.imageView.image = nil;
http://img29.imageshack.us/img29/1083/ekranresmi2013020301553.png
http://img502.imageshack.us/img502/5591/ekranresmi2013012919525.png

uitableviewcells are overlapping first 2 cells of 3 overlap

I have been trying to figure out if my cells are overlapping but I failed. My table contains 3 entries - the first 2 get overlapped but the 3rd one doesn't. I have searched on the net and found that variables should be defined locally. I have taken that advice but sadly, it didn't help.
Below is the code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIColor *rung;
if (indexPath.row%2 == 0) {
// 0.662745 0.662745 0.662745
rung=[UIColor colorWithRed:0.802745 green:0.802745 blue:0.802745 alpha:1];
color=NO;
}
else {
// 0.972549 0.972549 1
//0.411765 0.411765 0.411765
rung=[UIColor colorWithRed:0.862745 green:0.862745 blue:0.862745 alpha:1];
color=YES;
}
//static NSString *MyIdentifier = #"Identifier";
NSLog(#"====IndexPath is %d",indexPath.row);
ChatSlideDC *slide = [[HMMainManager getSharedInstance].currentMeeting.resumedChatMessages objectAtIndex:indexPath.section];
ChatMessageDC *message;
message = [[slide ChatMessageArray]objectAtIndex:indexPath.row];
NSLog(#"%i",indexPath.row);
NSLog(#"%#",message.senderEmail);
NSLog(#"====Message Type is %#",message.MessageType);
//--storing Email-ID for Pics
UIImage *avatar;
if(message.AttendeeID)
{
avatar= [(AppDelegate *)[[UIApplication sharedApplication]delegate] getAvatar:message.AttendeeID andAttendeEmail:message.senderEmail];
}
//
NSLog(#"%#",message.Message);
if ([message.MessageType isEqualToString: #"0"] || [message.MessageType isEqualToString:#"1"]) {
ChatCustomCell * cell = (ChatCustomCell *) [tableView dequeueReusableCellWithIdentifier:#"ChatCustomCell"];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"ChatCustomCell" owner:self options:nil];
cell = (ChatCustomCell*)[nib objectAtIndex:0];
}
// cell.backgroundImage.backgroundColor=rung;
UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
view.backgroundColor = rung;
view.opaque = YES;
cell.backgroundView = view;
[view release];
//cell.backgroundColor=rung;
cell.lblSaid.text =#"Said";
cell.lblName.text =message.SenderName;
cell.lblText.text =message.Message;
NSLog(#"manager strID: %# chat cell attendeeID %#",[HMMainManager getSharedInstance].currentMeeting.strAttendeeID,message.AttendeeID);
NSLog(#"%# == %#",message.AttendeeID,[HMMainManager getSharedInstance].currentMeeting.strAttendeeID);
[cell.imgThumbUserPic setImage:[UIImage imageNamed:#"updateProfileIco.png"]];
// if ([message.AttendeeID isEqualToString:[HMMainManager getSharedInstance].currentMeeting.strAttendeeID]) {
// cell.imgThumbUserPic.image = [MainManager getSharedInstance].userManager.userImage;
cell.imgThumbUserPic.image = avatar;
// }
cell.selectionStyle = UITableViewCellEditingStyleNone;
// [message release];
return cell;
}
if ([message.MessageType isEqualToString:#"2"] || [message.MessageType isEqualToString:#"3"] ) {
if ([message.MessageType isEqualToString:#"3"] || (message.question && [message.question length]>0)) {
//show asnwer cell
// AnswerCustomCell * cell = (AnswerCustomCell *) [tableView dequeueReusableCellWithIdentifier:#"AnswerCustomCell"];
NSMutableArray *answerquestArray= [[[HMMainManager getSharedInstance] currentMeeting]questionAnswerArray];
// UITableViewCell *newCell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:#"abc"];
int width=300,height=164,totalHeight;;
// AnswerMultipleCell * cell;
int questionIndex;
QuestionWithAnswers *qwa;
for (int i=0;i<answerquestArray.count;i++) {
qwa=[answerquestArray objectAtIndex:i];
NSLog(#"");
if ([qwa.questionID isEqualToString:message.QuestionID]) {
break;
}
}//end for
// newCell.frame=CGRectMake(0, totalHeight, width, height);
ChatMessageDC *answersInArr;
int i=0;
for (i=0;i<[qwa.answersMArray count];i++) {
answersInArr=[qwa.answersMArray objectAtIndex:i];
if([answersInArr.MessageId isEqualToString:message.MessageId])
{
break;
}
}
AnswerMultipleCell * cell = (AnswerMultipleCell *) [tableView dequeueReusableCellWithIdentifier:#"AnswerMultipleCell"];
if (cell == nil)
{
// NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"AnswerCustomCell" owner:self options:nil];
// cell = (AnswerCustomCell*)[nib objectAtIndex:0];
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"AnswerMultipleCell" owner:self options:nil];
cell = (AnswerMultipleCell*)[nib objectAtIndex:0];
}
UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
view.backgroundColor = rung;
view.opaque = YES;
cell.backgroundView = view;
[view release];
//answer here goes
cell.answerTxt.text=answersInArr.Message;
cell.userName.text=answersInArr.SenderName;
[cell.answerTxt flashScrollIndicators];
//question
NSLog(#"%#",message.MessageId);
NSLog(#"manager strID: %# ans cell attendeeID %#",[HMMainManager getSharedInstance].currentMeeting.strAttendeeID,message.AttendeeID);
[cell.userPic setImage:[UIImage imageNamed:#"updateProfileIco.png" ]];
// [cell.quePic setImage:[UIImage imageNamed:#"updateProfileIco.png" ]];
//if ([message.AttendeeID isEqualToString:[HMMainManager getSharedInstance].currentMeeting.strAttendeeID]) {
avatar= [(AppDelegate *)[[UIApplication sharedApplication]delegate] getAvatar:[qwa.attendeIDMArray objectAtIndex:i] andAttendeEmail:[qwa.attendeEmails objectAtIndex:i]];
NSLog(#"----------:: %# == %# and message:%#",message.AttendeeID ,[HMMainManager getSharedInstance].currentMeeting.strAttendeeID,message.Message);
// cell.ansPic.image = [MainManager getSharedInstance].userManager.userImage;
cell.userPic.image = avatar;
// }
NSLog(#"manager strID: %# ans cell attendeeID %#",[HMMainManager getSharedInstance].currentMeeting.strAttendeeID,message.QuestionID);
// {
NSLog(#"------------:: %# == %# and message:%#",message.questionAttendeeID ,[HMMainManager getSharedInstance].currentMeeting.strAttendeeID,message.Message);
// cell.quePic.image = [MainManager getSharedInstance].userManager.userImage;
// cell.quePic.image = avatar;
// }
//}//end answersArray
return cell;
}
else {
//show question cell
QuestionCustomCell * cell = (QuestionCustomCell *) [tableView dequeueReusableCellWithIdentifier:#"QuestionCustomCell"];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"QuestionCustomCell" owner:self options:nil];
cell = (QuestionCustomCell*)[nib objectAtIndex:0];
}
UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
view.backgroundColor = rung;
view.opaque = YES;
cell.backgroundView = view;
[view release];
cell.lblSaid.text =#"Asked";
cell.lblName.text =message.SenderName;
NSLog(#"Question is %#", message.question);
cell.lblText.text =message.Message;
[cell.lblText flashScrollIndicators];
// cell.lblAnswerQuestion.hidden = NO;
if (!message.answered) {
cell.lblAnswerQuestion.hidden = NO;
cell.userInteractionEnabled = YES;
}else {
cell.lblAnswerQuestion.hidden = YES;
cell.userInteractionEnabled = NO;
}
// cell.userInteractionEnabled = YES;
[[HMMainManager getSharedInstance].currentMeeting.questionDict setObject:message.AttendeeID forKey:message.MessageId];
NSLog(#"manager strID: %# ques cell attendeeID %#",[HMMainManager getSharedInstance].currentMeeting.strAttendeeID,message.AttendeeID);
[cell.imgThumbUserPic setImage:[UIImage imageNamed:#"updateProfileIco.png"]];
// if ([message.AttendeeID isEqualToString:[HMMainManager getSharedInstance].currentMeeting.strAttendeeID]) {
// cell.imgThumbUserPic.image = [MainManager getSharedInstance].userManager.userImage;
cell.imgThumbUserPic.image = avatar;
// }
cell.tvAnswer.delegate = self;
NSMutableString* finalSec = [NSString stringWithFormat:#"%d",indexPath.section];
for (NSInteger x=0; x<3; x++) {
if (finalSec.length <3) {
finalSec = [NSString stringWithFormat:#"0%#",finalSec];
}
}
NSLog(#"%#", finalSec);
NSString* tag = [NSString stringWithFormat:#"%d%#",indexPath.row+1, finalSec];
NSLog(#"tag value %d",[tag intValue]);
cell.btnAnswer.tag = [tag intValue];//indexPath.row + 1000 + indexPath.section;
cell.tvAnswer.tag = [tag intValue];
cell.selectionStyle = UITableViewCellEditingStyleNone;
[cell.btnAnswer addTarget:self action:#selector(answerButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
// [message release];
return cell;
}
}
// [message release];
return nil;
}
If you have custom (non 44 point height) cells, then you need to implement - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

getting wrong value in custom uitableViewCell

Hello all I am implementing a chat Messenger. i am facing a strange situation. I have a custom tableview cell it works perfectly fine when i scroll normally. But if i scroll very fast like a crazy man the images of users get mixed. I cannot figure put what can be the reason any help fellows and thx in advance
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIColor *rung;
if (indexPath.row%2 == 0) {
// 0.662745 0.662745 0.662745
rung=[UIColor colorWithRed:0.802745 green:0.802745 blue:0.802745 alpha:1];
color=NO;
}
else {
// 0.972549 0.972549 1
//0.411765 0.411765 0.411765
rung=[UIColor colorWithRed:0.862745 green:0.862745 blue:0.862745 alpha:1];
color=YES;
}
//static NSString *MyIdentifier = #"Identifier";
NSLog(#"====IndexPath is %d",indexPath.row);
ChatSlideDC *slide = [[HMMainManager getSharedInstance].currentMeeting.resumedChatMessages objectAtIndex:indexPath.section];
ChatMessageDC *message;
message = [[slide ChatMessageArray]objectAtIndex:indexPath.row];
NSLog(#"====Message Type is %#",message.MessageType);
NSLog(#"%#",message.Message);
if ([message.MessageType isEqualToString: #"0"] || [message.MessageType isEqualToString:#"1"]) {
ChatCustomCell * cell = (ChatCustomCell *) [tableView dequeueReusableCellWithIdentifier:#"ChatCustomCell"];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"ChatCustomCell" owner:self options:nil];
cell = (ChatCustomCell*)[nib objectAtIndex:0];
}
// cell.backgroundImage.backgroundColor=rung;
UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
view.backgroundColor = rung;
view.opaque = YES;
cell.backgroundView = view;
[view release];
//cell.backgroundColor=rung;
cell.lblSaid.text =#"Said";
cell.lblName.text =message.SenderName;
cell.lblText.text =message.Message;
NSLog(#"manager strID: %# chat cell attendeeID %#",[HMMainManager getSharedInstance].currentMeeting.strAttendeeID,message.AttendeeID);
NSLog(#"%# == %#",message.AttendeeID,[HMMainManager getSharedInstance].currentMeeting.strAttendeeID);
if ([message.AttendeeID isEqualToString:[HMMainManager getSharedInstance].currentMeeting.strAttendeeID]) {
cell.imgThumbUserPic.image = [MainManager getSharedInstance].userManager.userImage;
}
cell.selectionStyle = UITableViewCellEditingStyleNone;
// [message release];
return cell;
}
if ([message.MessageType isEqualToString:#"2"] || [message.MessageType isEqualToString:#"3"] ) {
if ([message.MessageType isEqualToString:#"3"] || (message.question && [message.question length]>0)) {
//show asnwer cell
AnswerCustomCell * cell = (AnswerCustomCell *) [tableView dequeueReusableCellWithIdentifier:#"AnswerCustomCell"];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"AnswerCustomCell" owner:self options:nil];
cell = (AnswerCustomCell*)[nib objectAtIndex:0];
}
UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
view.backgroundColor = rung;
view.opaque = YES;
cell.backgroundView = view;
[view release];
//answer here goes
cell.answerdBy.text = message.SenderName;
cell.answerText.text = message.Message;
[cell.answerText flashScrollIndicators];
//question
cell.questionedBy.text = message.QuestionBy;
cell.questionText.text = message.question;
[cell.questionText flashScrollIndicators];
NSLog(#"%#",message.MessageId);
NSLog(#"manager strID: %# ans cell attendeeID %#",[HMMainManager getSharedInstance].currentMeeting.strAttendeeID,message.AttendeeID);
if ([message.AttendeeID isEqualToString:[HMMainManager getSharedInstance].currentMeeting.strAttendeeID]) {
// if ([message.SenderName isEqualToString:compName] ) {
NSLog(#"----------:: %# == %# and message:%#",message.AttendeeID ,[HMMainManager getSharedInstance].currentMeeting.strAttendeeID,message.Message);
cell.ansPic.image = [MainManager getSharedInstance].userManager.userImage;
// }
}
NSLog(#"manager strID: %# ans cell attendeeID %#",[HMMainManager getSharedInstance].currentMeeting.strAttendeeID,message.QuestionID);
// NSString *qustWalaID=[[HMMainManager getSharedInstance].currentMeeting.questionDict objectForKey:message.QuestionID];
// NSLog(#"%#",questionDict);
if ([message.questionAttendeeID isEqualToString:[HMMainManager getSharedInstance].currentMeeting.strAttendeeID])
{
// if ([message.QuestionBy isEqualToString:compName] ) {
NSLog(#"------------:: %# == %# and message:%#",message.questionAttendeeID ,[HMMainManager getSharedInstance].currentMeeting.strAttendeeID,message.Message);
cell.quePic.image = [MainManager getSharedInstance].userManager.userImage;
// }
}
// tempChatMessageDC=message;
// tempAnswerCustomCell=cell;
// [message release];
return cell;
}
else {
//show question cell
QuestionCustomCell * cell = (QuestionCustomCell *) [tableView dequeueReusableCellWithIdentifier:#"QuestionCustomCell"];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"QuestionCustomCell" owner:self options:nil];
cell = (QuestionCustomCell*)[nib objectAtIndex:0];
}
UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
view.backgroundColor = rung;
view.opaque = YES;
cell.backgroundView = view;
[view release];
cell.lblSaid.text =#"Asked";
cell.lblName.text =message.SenderName;
NSLog(#"Question is %#", message.question);
cell.lblText.text =message.Message;
[cell.lblText flashScrollIndicators];
// cell.lblAnswerQuestion.hidden = NO;
if (!message.answered) {
cell.lblAnswerQuestion.hidden = NO;
cell.userInteractionEnabled = YES;
}else {
cell.lblAnswerQuestion.hidden = YES;
cell.userInteractionEnabled = NO;
}
// cell.userInteractionEnabled = YES;
[[HMMainManager getSharedInstance].currentMeeting.questionDict setObject:message.AttendeeID forKey:message.MessageId];
NSMutableDictionary *tmpDoct=[HMMainManager getSharedInstance].currentMeeting.questionDict ;
// [questionDict setObject:message.AttendeeID forKey:message.MessageId];
NSLog(#"%#",tmpDoct );
NSLog(#"manager strID: %# ques cell attendeeID %#",[HMMainManager getSharedInstance].currentMeeting.strAttendeeID,message.AttendeeID);
if ([message.AttendeeID isEqualToString:[HMMainManager getSharedInstance].currentMeeting.strAttendeeID]) {
cell.imgThumbUserPic.image = [MainManager getSharedInstance].userManager.userImage;
}
cell.tvAnswer.delegate = self;
NSMutableString* finalSec = [NSString stringWithFormat:#"%d",indexPath.section];
for (NSInteger x=0; x<3; x++) {
if (finalSec.length <3) {
finalSec = [NSString stringWithFormat:#"0%#",finalSec];
}
}
NSLog(#"%#", finalSec);
NSString* tag = [NSString stringWithFormat:#"%d%#",indexPath.row+1, finalSec];
NSLog(#"tag value %d",[tag intValue]);
cell.btnAnswer.tag = [tag intValue];//indexPath.row + 1000 + indexPath.section;
cell.tvAnswer.tag = [tag intValue];
cell.selectionStyle = UITableViewCellEditingStyleNone;
[cell.btnAnswer addTarget:self action:#selector(answerButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
// [message release];
return cell;
}
}
// [message release];
return nil;
}
You should correctly use cell's reusing. You have code fragment:
if ([message.AttendeeID isEqualToString:[HMMainManager getSharedInstance].currentMeeting.strAttendeeID]) {
cell.imgThumbUserPic.image = [MainManager getSharedInstance].userManager.userImage;
}
There is you don't process other variants. You should set user pic in any case
if ([message.AttendeeID isEqualToString:[HMMainManager getSharedInstance].currentMeeting.strAttendeeID]) {
cell.imgThumbUserPic.image = [MainManager getSharedInstance].userManager.userImage;
} else {
cell.imgThumbUserPic.image = nil; //or set it with another image
}

Resources