UITableViewCell not appearing/reusing correctly from NIB - iphone

I have created a custom UITableViewCell from a NIB. Everything appears when the rowHeight is not set (albeit, everything is squished). I am not sure if I am reusing and creating the cells properly:
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = #"ARCell";
ARObject *myARObject;
myARObject = [items objectAtIndex:indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:#"ARCell" owner:self options:nil];
cell = arCell;
self.arCell = nil;
}
UILabel *label;
label = (UILabel *)[cell viewWithTag:0];
label.text = [NSString stringWithFormat:#"%#", myARObject.username];
label = (UILabel *)[cell viewWithTag:1];
label.text = [NSString stringWithFormat:#"%#", myARObject.created_at];
label = (UILabel *)[cell viewWithTag:2];
label.text = [NSString stringWithFormat:#"%#", myARObject.articleTitle];
label = (UILabel *)[cell viewWithTag:3];
label.text = [NSString stringWithFormat:#"%#", myARObject.intro_text];
return cell;
}
- (CGFloat)tableView:(UITableView *)tblView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{ CGFloat rowHeight = 105;
return rowHeight;
}
Problems:
Not all labels appear when rowHeight is set. If rowHeight isn't set, labels are squished
When rowHeight is not set, selecting an item shows all of the labels

Remove the else clause

You call loadNibNamed, but don't store result anywhere! Can't understand why your code works at all... Anyway, writing blind I would try something like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *MyIdentifier = #"ARCell";
ARObject *myARObject = [items objectAtIndex:indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"ARCell" owner:self options:nil];
cell = (UITableViewCell *)[nib objectAtIndex:0];
}
UILabel *label;
label = (UILabel *)[cell viewWithTag:0];
label.text = [NSString stringWithFormat:#"%#", myARObject.username];
label = (UILabel *)[cell viewWithTag:1];
label.text = [NSString stringWithFormat:#"%#", myARObject.created_at];
label = (UILabel *)[cell viewWithTag:2];
label.text = [NSString stringWithFormat:#"%#", myARObject.articleTitle];
label = (UILabel *)[cell viewWithTag:3];
label.text = [NSString stringWithFormat:#"%#", myARObject.intro_text];
return cell;
}
- (CGFloat)tableView:(UITableView *)tblView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 105.0;
}

Related

custom label value is disappearing when scrolling table view

I am new to iphone. my cutomcell label value is disappearing when I scroll the table view.
Again it appears when I click on that cell.
Can anyone help me?
Thanks in Advance.
//table view in view controller created in xib
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"ListOfProductsCell";
ListOfProductsCell *cell = (ListOfProductsCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell==nil) {
NSArray *nib =[[NSBundle mainBundle] loadNibNamed:#"ListOfProductsCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
productItemDit=[productListArry objectAtIndex:indexPath.row];
NSString *offerStr= [NSString stringWithFormat:#"%.2f",[[productItemDit objectForKey:#"offer"] floatValue]];
NSString *fullCostStr=[[currencyCodeStr stringByAppendingString:#" "] stringByAppendingString:offerStr];
NSLog(#"%#",fullCostStr);
cell.itemCostLbl.text=fullCostStr;
} else {
cell.itemStepper = (UIStepper *) [cell viewWithTag:2];
cell.itemAddedLbl =(UILabel*)[cell viewWithTag:1];
}
if (tableView == self.searchDisplayProduct.searchResultsTableView) {
searchProductItemDit=[searchProductListArry objectAtIndex:indexPath.row];
NSLog(#"searchdit:%#",searchProductItemDit);
cell.itemNameLbl.text= [searchProductItemDit objectForKey:#"name"];
self.searchDisplayProduct.searchResultsTableView.separatorColor=[UIColor colorWithRed:200.0 green:0.0 blue:0.0 alpha:1.0];
} else {
productItemDit=[productListArry objectAtIndex:indexPath.row];
NSLog(#"dit:%#",productItemDit);
cell.itemNameLbl.text=[productItemDit objectForKey:#"name"];
}
cell.itemAddedLbl.text = [[NSString alloc] initWithFormat:#"%d",itemCount];
cell.itemImg.image = [UIImage imageNamed:#"profp.jpg"];
return cell;
}
Solved by doing like this
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"ListOfProductsCell";
ListOfProductsCell *cell = (ListOfProductsCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell==nil) {
NSArray *nib =[[NSBundle mainBundle] loadNibNamed:#"ListOfProductsCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
} else {
cell.itemStepper = (UIStepper *) [cell viewWithTag:2];
cell.itemAddedLbl =(UILabel*)[cell viewWithTag:1];
}
if (tableView == self.searchDisplayProduct.searchResultsTableView) {
cell.itemNameLbl.text= [[searchProductListArry objectAtIndex:indexPath.row] objectForKey:#"name"];
} else {
cell.itemNameLbl.text=[[productListArry objectAtIndex:indexPath.row] objectForKey:#"name"];
}
cell.itemCostLbl.text=[NSString stringWithFormat:#"%# %.2f", currencyCodeStr , [[[productListArry objectAtIndex:indexPath.row] objectForKey:#"offer"] floatValue]];
cell.itemAddedLbl.text = [[NSString alloc] initWithFormat:#"%d",itemCount];
cell.itemImg.image = [UIImage imageNamed:#"profp.jpg"];
return cell;
}
As you haven't post much of the information this is my guess.when you scroll table view it internally calls the reloadData method . You need to use reuse Identifier to preserve the state of the cell. You can initialize the cell in cellForRowAtIndexPath like :
static NSString *cellIdentifier = #"cellID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
// or cell initializing logic here for the custom cell
}
in case of custom cell add reuse identifier in the xib and use it in your cellForRowAtIndexPath method

tableView not reusing cell properly

This is my code for a tableView
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CounterCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:#"CounterCell" owner:self options:nil];
cell = nibLoadedCell2;
}
Program *program = [memory getProgramAtIndex:[memory chosenProgram]];
NSMutableArray *arrayOfIntervals = [[NSMutableArray alloc] init];
arrayOfIntervals = program.arrayOfIntervals;
NSMutableDictionary *interval = [arrayOfIntervals objectAtIndex:indexPath.row];
UITextField *intervalName = (UITextField *)[cell viewWithTag:1];
intervalName.text = [interval objectForKey:#"nameOfInterval"];
[intervalName addTarget:self action:#selector(returnKey:) forControlEvents:UIControlEventEditingDidEndOnExit];
[intervalName addTarget:self action:#selector(editingEnded:) forControlEvents:UIControlEventEditingDidEnd];
[intervalName addTarget:self action:#selector(editTextField:) forControlEvents:UIControlEventEditingDidBegin];
timeInSeconds = [[interval objectForKey:#"timeInSeconds"] intValue];
if (indexPath.row == 0) {
firstCellGeneralTime = timeInSeconds;
}
NSString *time = [self timeTextWithTimeInSeconds:timeInSeconds];
UILabel *intervalTime = (UILabel *)[cell viewWithTag:2];
intervalTime.text = time;
if (indexPath.row == 0) {
majorLabel.text = time;
}
UILabel *hourString = (UILabel *)[cell viewWithTag:11];
hourString.text = [NSString stringWithFormat:#"%d",hoursInt];
UILabel *minuteString = (UILabel *)[cell viewWithTag:12];
minuteString.text = [NSString stringWithFormat:#"%d",minutesInt];
UILabel *secondString = (UILabel *)[cell viewWithTag:13];
secondString.text = [NSString stringWithFormat:#"%d",secondsInt];
UIButton *editTime = (UIButton *)[cell viewWithTag:21];
[editTime addTarget:self action:#selector(openPicker:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
My table view shows a bit less than 3 cells, and on a certain point i delete the first cell and than the 4th cell is showing up.
The problem is that the 4th cell is exactly like my 3rd cell, although it should be different.
It does reuse it as it should.
I don't know what i've done wrong.
This is the code for the deletion of a cell:
NSIndexPath *firstCellIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
NSArray *arrayOfIndexPath = [[NSArray alloc] initWithObjects:firstCellIndexPath, nil];
[atableView deleteRowsAtIndexPaths:arrayOfIndexPath withRowAnimation:UITableViewRowAnimationTop];
You have to remove the first interval from the program.arrayOfIntervals array while deleting the cell.
Found it, the problematic code is:
Program *program = [memory getProgramAtIndex:[memory chosenProgram]];
NSMutableArray *arrayOfIntervals = [[NSMutableArray alloc] init];
arrayOfIntervals = program.arrayOfIntervals;
NSMutableDictionary *interval = [arrayOfIntervals objectAtIndex:indexPath.row];
I am creating a new program and get the details of the intervals from it, instead of using the program i removed the first interval from…
I feel so dumb...

UIlabel gets shrink on scrolling UiTableView

I have two UILabel in side of UICell, which contains dynamic text so i need to resize its frame according to content, for which im using [string sizeWithFont] method to calculate the height of label view's frame inside of TableView heightForRowAtIndexPath to set the height of cell according to label height. Now what the problem is when i scroll my table, label inside of cell starts to shrink if i remove [label sizeToFit] method it doesn't shrink but from that my labels are getting overlapped which looks very messy. Where i am wrong please guide me..
here is my code for cellRowAtIndexPath method
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"cell");
BOOL ente = FALSE;
static NSString *CellIdentifier = #"CustomCell";
CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:nil options:nil];
for (id currentObject in topLevelObjects){
if ([currentObject isKindOfClass:[UITableViewCell class]]){
cell = (CustomCell *) currentObject;
ente = TRUE;
break;
}
}
}
/*
[cell.title sizeToFit];
[cell.dataTime sizeToFit];
CGSize size1 = [[mainEventArray objectAtIndex:[indexPath row]] sizeWithFont:[UIFont systemFontOfSize:13.0f] constrainedToSize:CGSizeMake(275, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
cell.title.frame = CGRectMake(50, 6, size1.width, size1.height);
CGSize size2 = [[mainEventTimeArray objectAtIndex:[indexPath row]] sizeWithFont:[UIFont systemFontOfSize:11.0f] constrainedToSize:CGSizeMake(275, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
cell.dataTime.frame = CGRectMake(50, 24, size2.width, size2.height);
*/
cell.title.text = [mainEventArray objectAtIndex:[indexPath row]];
cell.dataTime.text = [mainEventTimeArray objectAtIndex:[indexPath row]];
//if (ente) {
// NSLog(#"helllloo");
[cell.title sizeToFit];
[cell.dataTime sizeToFit];
//}
return cell;
}
and for heightForRowAtIndexPath method
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CustomCell";
CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
{
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:nil options:nil];
for (id currentObject in topLevelObjects){
if ([currentObject isKindOfClass:[UITableViewCell class]]){
cell = (CustomCell *) currentObject;
break;
}
}
}
}
CGSize size1 = [[mainEventArray objectAtIndex:[indexPath row]] sizeWithFont:[UIFont systemFontOfSize:13.0f] constrainedToSize:CGSizeMake(230, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
cell.title.frame = CGRectMake(0, 0, size1.width, size1.height);
CGSize size2 = [[mainEventTimeArray objectAtIndex:[indexPath row]] sizeWithFont:[UIFont systemFontOfSize:11.0f] constrainedToSize:CGSizeMake(230, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
cell.dataTime.frame = CGRectMake(0, 0, size2.width, size2.height);
//NSLog(#"%f", size1.height + size2.height + 20);
return size1.height + size2.height + 20;
//NSString *str = [heights_ objectAtIndex:[indexPath row]];
// return [str floatValue] ;
}
Instead of doing your own customization. Try with dynamic uitableviewcell height. You will find really usefull & comparatively easier than what you have done.
You can check it here : http://www.cimgf.com/2009/09/23/uitableviewcell-dynamic-height/ with full of explanation. Enjoy programming.
In your case you need to set the height of cell based on the label.
Check the link :
http://dcraziee.wordpress.com/2013/05/22/calculate-size-of-uillabel-base-on-text-in/
There is a function named
-(CGFloat)getHeightForLabel:(NSString *)_str font:(UIFont *)fontOfObject
Use that function to calculate height as :
-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
CGFloat _height = [self getHeightForLabel:self.label.text font:[self.label font]];
return _height;
}
and do the same while creating and adding label in the cell.
I hope this will help.
NSString *reuseIdentifier = #"EventTitleCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
cell=nil;
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier] ;
}
Try This code.
label.numberOfLines = 0; // allows label to have as many lines as needed
label.text = #"some long text";
[label sizeToFit];
NSLog(#"Label's frame is: %#", NSStringFromCGRect(label.frame));
For reference : click here

Why my UITableView not smooth when scroll first time?

My table view cell has four labels.
The table view is not smooth when scroll in first time. After all cells displayed one time, the scrolling is so smooth with no problem.
So I thought the problem is the speed of loading one cell in the first time.
I have reuse cell but the problem is not solved. Please help me! Thanks so much!
Here is my code:
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *MyIdentifier = #"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
NSArray *views = [[NSBundle mainBundle] loadNibNamed:#"ForumListTableViewCell" owner:self options:nil];
cell = [views objectAtIndex:0];
}
NSDictionary *cate = [_forums objectAtIndex:indexPath.section];
NSArray *forumsInCate = [cate objectForKey:#"forums"];
NSDictionary *forumInfo = [forumsInCate objectAtIndex:indexPath.row];
// title1
UILabel *forumTitleLabel = (UILabel *)[cell viewWithTag:1];
forumTitleLabel.text = [forumInfo objectForKey:#"name"];
// master
UILabel *masterLabel = (UILabel *)[cell viewWithTag:2];
NSString *master = [forumInfo objectForKey:#"moderators"];
masterLabel.text = master;
// title2
UILabel *threadTitleLabel = (UILabel *)[cell viewWithTag:3];
NSString *lastPostTitle;
NSDictionary *lastPostInfo = [forumInfo objectForKey:#"lastpost"];
lastPostTitle = [lastPostInfo objectForKey:#"subject"];
threadTitleLabel.text = lastPostTitle;
// author
UILabel *authorLabel = (UILabel *)[cell viewWithTag:4];
authorLabel.text = [NSString stringWithFormat:#"%# / %#",
[forumInfo objectForKey:#"threads"],
[forumInfo objectForKey:#"posts"]
];
return cell;
}
NSArray *views = [[NSBundle mainBundle] loadNibNamed:#"ForumListTableViewCell" owner:self options:nil];
on .h
NSArray *views;
on .m
-(void)viewDidLoad
{
[super viewDidLoad];
views = [[NSBundle mainBundle] loadNibNamed:#"ForumListTableViewCell" owner:self options:nil];
}
- (void)dealloc
{
//--- other object ----
[views release];
[super dealloc];
}

heightForRowAtIndexPath crashes

I have the following code:
- (CGFloat)tableView:(UITableView *) tableView heightForRowAtIndexPath:(NSIndexPath *) indexPath{
TestCell* cell = (ConvoreCell *) [tableView cellForRowAtIndexPath:indexPath];
CGSize textSize = [[cell text] sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake([tableView frame].size.width - 20, 500)];
return 80;
}
It crashes on the cellForRowAtIndexPath, why is this? The log doesn't tell me anything. Here's my cellForRowAtIndexPath method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"ConvoreCell";
AsyncImageView *asyncImageView = nil;
TestCell * cell = (TestCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"TestCell" owner:nil options:nil];
for (id currentObject in topLevelObjects){
if ([currentObject isKindOfClass:[UITableViewCell class]]){
cell = (ConvoreCell *) currentObject;
break;
}
}
asyncImageView = [[[AsyncImageView alloc] init] autorelease];
asyncImageView.imageview = cell.icon;
}
else {
asyncImageView = (AsyncImageView *) [cell.contentView viewWithTag:ASYNC_IMAGE_TAG];
}
NSMutableDictionary *cellValue = [results objectAtIndex:indexPath.row];
NSString *picURL = [[cellValue objectForKey:#"user"] objectForKey:#"img"];
if ([picURL isEqualToString:#"https://secure.gravatar.com/avatar/1f043010eb1652b3fab3678167dc0487/?default=https%3A%2F%2Fconvore.com%2Fmedia%2Fimages%2Feric.png&s=80"])
picURL = #"https://test.com/media/images/eric.png";
[asyncImageView loadImageFromURL:[NSURL URLWithString:picURL]];
cell.title.text = [cellValue objectForKey:#"message"];
cell.info.text = [NSString stringWithFormat:#"%# %# days ago", [[cellValue objectForKey:#"user"] objectForKey:#"username"], [cellValue objectForKey:#"date_created"] ];
return cell;
}
All I want to do is to resize the height of the cell according to the cell.title.text....
It's wrong to call cellForRowAtIndexPath: manually. You have to store those strings separately in array and obtain them from there.
A rule of thumb: don't call framework callbacks manually.