I am new to iPhone developer,
I am using UITableView, i want total 6 labels in my Cell of UITableView 3 label on L.H.S and 3 label on R.H.S
Here is my code snippet,
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 180;
}
- (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];
CGRect frameL;
frameL.origin.x = 10;
frameL.origin.y = 10;
frameL.size.height = 50;
frameL.size.width = 200;
CGRect frameR;
frameR.origin.x = 200;
frameR.origin.y = 10;
frameR.size.height = 40;
frameR.size.width = 180;
UILabel *AlertNameLHS = [[UILabel alloc] initWithFrame:frameL];
AlertNameLHS.font=[UIFont systemFontOfSize:16.0];
AlertNameLHS.backgroundColor=[UIColor clearColor];
AlertNameLHS.textColor=[UIColor redColor];
AlertNameLHS.text=#"Alert Name :";
[cell.contentView addSubview:AlertNameLHS];
frameL.origin.y += 60;
UILabel *AlertMonthLHS = [[UILabel alloc] initWithFrame:frameL];
AlertMonthLHS.font=[UIFont systemFontOfSize:16.0];
AlertMonthLHS.backgroundColor=[UIColor clearColor];
AlertMonthLHS.textColor=[UIColor redColor];
AlertNameLHS.text=#"Alert Month :";
[cell.contentView addSubview:AlertMonthLHS];
frameL.origin.y += 120;
UILabel *DueOnLHS = [[UILabel alloc] initWithFrame:frameL];
DueOnLHS.font=[UIFont systemFontOfSize:16.0];
AlertNameLHS.text=#"Due On :";
[cell.contentView addSubview:DueOnLHS];
AlertNameRHS = [[UILabel alloc] initWithFrame:frameR];
AlertNameRHS.backgroundColor=[UIColor greenColor];
AlertNameRHS.textColor=[UIColor redColor];
AlertNameRHS.textColor=[UIColor redColor];
AlertNameRHS.font=[UIFont systemFontOfSize:18.0];
[cell.contentView addSubview:AlertNameRHS];
frameL.origin.y += 80;
AlertMonthRHS = [[UILabel alloc] initWithFrame:frameR];
AlertMonthRHS.font=[UIFont systemFontOfSize:18.0];
[cell.contentView addSubview:AlertMonthRHS];
frameL.origin.y += 120;
DueOnRHS = [[UILabel alloc] initWithFrame:frameR];
DueOnRHS.font=[UIFont systemFontOfSize:18.0];
[cell.contentView addSubview:DueOnRHS];
}
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
AlertNameRHS.text = [Myarray objectAtIndex:indexPath.row];
return cell;
}
but i am unable to see my UILabel properly.
Any help will be appreciated.
EDIT: :
See the corrected code:
- (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];
CGRect frameL;
frameL.origin.x = 10;
frameL.origin.y = 10;
frameL.size.height = 50;
frameL.size.width = 200;
CGRect frameR;
frameR.origin.x = 200;
frameR.origin.y = 10;
frameR.size.height = 40;
frameR.size.width = 180;
UILabel *AlertNameLHS = [[UILabel alloc] initWithFrame:frameL];
AlertNameLHS.font=[UIFont systemFontOfSize:16.0];
AlertNameLHS.backgroundColor=[UIColor clearColor];
AlertNameLHS.textColor=[UIColor redColor];
AlertNameLHS.text=#"Alert Name :";
[cell.contentView addSubview:AlertNameLHS];
frameL.origin.y += 60;
NSLog(#"fr %f", frameL.origin.y);
UILabel *AlertMonthLHS = [[UILabel alloc] initWithFrame:frameL];
AlertMonthLHS.font=[UIFont systemFontOfSize:16.0];
AlertMonthLHS.backgroundColor=[UIColor clearColor];
AlertMonthLHS.textColor=[UIColor redColor];
AlertMonthLHS.text=#"Alert Month :";
[cell.contentView addSubview:AlertMonthLHS];
frameL.origin.y += 60;
NSLog(#"fr %f", frameL.origin.y);
UILabel *DueOnLHS = [[UILabel alloc] initWithFrame:frameL];
DueOnLHS.font=[UIFont systemFontOfSize:16.0];
DueOnLHS.text=#"Due On :";
[cell.contentView addSubview:DueOnLHS];
AlertNameRHS = [[UILabel alloc] initWithFrame:frameR];
AlertNameRHS.backgroundColor=[UIColor greenColor];
AlertNameRHS.textColor=[UIColor redColor];
AlertNameRHS.textColor=[UIColor redColor];
AlertNameRHS.font=[UIFont systemFontOfSize:18.0];
AlertNameRHS.text = #"l1";
[cell.contentView addSubview:AlertNameRHS];
frameR.origin.y += 60;
AlertMonthRHS = [[UILabel alloc] initWithFrame:frameR];
AlertMonthRHS.font=[UIFont systemFontOfSize:18.0];
AlertMonthRHS.text =#"l2";
[cell.contentView addSubview:AlertMonthRHS];
frameR.origin.y += 60;
DueOnRHS = [[UILabel alloc] initWithFrame:frameR];
DueOnRHS.font=[UIFont systemFontOfSize:18.0];
DueOnRHS.text = #"l3";
[cell.contentView addSubview:DueOnRHS];
}
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
AlertNameRHS.text = [NSString stringWithFormat:#"%d",indexPath.row];
return cell;
}
You've made too many mistakes:
The LHS1 is visible, but you override it's text with LHS3 text: AlertNameLHS.text=#"Due On :";
The LHS2 isn't visible because you only initialize it and add as a subview, configured LHS1 instead of it
The LHS3 is not visible because the cell height is 180 and it's y coordinate is 190, you also don't set it's text setting the LHS1 text instead.
The RHS labels frames are incorrect and out of cell frame, you are supposed to use frameR but using frameL, i also suggest you want to add 60 pixels to y coordinate on every step.
To perform this kind of work, I would suggest you to create one custom cell . (Add New file -> Objective-C class -> UItableViewCell)
Define 6 Lables with property
#import <UIKit/UIKit.h>
#interface DemoCell : UITableViewCell
{
IBOutlet UILabel *lblOne;
}
#property (nonatomic,retain) IBOutlet UILabel *lblOne;
Now Create a new Empty View (Only nib file) name it Democell (for your convenience)
Now in that Delete the view from nib file and from the Library drag and Drop a Table View Cell at the place of your View in nib file.
Now select your tableviewcell , and in its identity inspector , change its class to DemoCell
So This will link your nib file with custom cell class..
Now in the nib file ,drag&drop 6 label, position them as per your requirement , and in the file owner link all the lbls with lblOne,lblTwo ,,,,....
Now your custom cell is complete.
To use this cell in your table's cellforrowatindexpath
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"cell";
DemoCell *cell= (DemoCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell ==nil)
{
cell=[[[NSBundle mainBundle]loadNibNamed:#"DemoCell" owner:self options:nil] lastObject];
}
cell.lblone.textlabel.text = #"lblOne";
Define 6 labels and set frames for that.
Then, addSubView to the tableViewCell contentView.
Related
I have a UITableView with regular UITableViewCell, but I don't use any of UITableViewCell's lables. I just use the cell to embed a label and a UITextField to input some data. Problem is when you scroll up or scroll down and the UITableviewCell redraws itself, it draws an overlapping UITextFieldView over the old one and you see doubles! I'm thinking that maybe since I do put these UITextFields into a dictionary, it might save the textfield with a strong pointer, and try to make another one and just overlap. Anyone have any suggestions?
Here is my code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"ProductCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSDictionary *product = [self.products objectAtIndex:indexPath.row];
NSDictionary *orderpoint = [self.orderpoints objectAtIndex:indexPath.row];
cell.textLabel.text = #""; //black out text
CGFloat calculatedHeight = [self tableView:tableView heightForRowAtIndexPath:indexPath];
UILabel *productLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, cell.bounds.size.width - 50.0, calculatedHeight)];
productLabel.text = [[NSString alloc] initWithFormat:#"%#. %#",
[orderpoint objectForKey:#"sequence_nr"], [product objectForKey:#"name"]];
//word wrapping
productLabel.lineBreakMode = UILineBreakModeWordWrap;
productLabel.numberOfLines = 0; //infinite number of lines
productLabel.font = [UIFont fontWithName:#"Helvetica" size:14.0];
[cell.contentView addSubview:productLabel];
//create the cell's textfield
UITextField *cellTextField = [[UITextField alloc] initWithFrame:CGRectMake(cell.bounds.size.width - 50, cell.bounds.size.height - 30, 50, calculatedHeight - 20)];
cellTextField.adjustsFontSizeToFitWidth = YES;
cellTextField.textColor = [UIColor blackColor];
cellTextField.keyboardType = UIKeyboardTypeNumberPad; // will only need to end a count
cellTextField.returnKeyType = UIReturnKeyDone; // TODO make it go to the next items key, or make it exit out
cellTextField.backgroundColor = [UIColor whiteColor];
cellTextField.textAlignment = UITextAlignmentLeft; //align to the right
//cellTextField.delegate = self; //will need to set delegate, maybe
cellTextField.clearButtonMode = UITextFieldViewModeNever;
cellTextField.enabled = YES;
cellTextField.borderStyle = UITextBorderStyleRoundedRect; //add bezel rounded look to textfield
cellTextField.delegate = self;
[cell.contentView addSubview: cellTextField]; //add the textfield to the cell
// save to dictionary, using a dictionary because not certain if this is created in order to use an Array
[self.textFieldDict setObject:cellTextField forKey:[[NSNumber alloc] initWithInteger:indexPath.row]];
return cell;
}
You have not initialized your cell.Try this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"ProductCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//It will check whether cell in there or not, then deque the cell...
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
NSDictionary *product = [self.products objectAtIndex:indexPath.row];
NSDictionary *orderpoint = [self.orderpoints objectAtIndex:indexPath.row];
cell.textLabel.text = #""; //black out text
CGFloat calculatedHeight = [self tableView:tableView heightForRowAtIndexPath:indexPath];
UILabel *productLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, cell.bounds.size.width - 50.0, calculatedHeight)];
productLabel.text = [[NSString alloc] initWithFormat:#"%#. %#",
[orderpoint objectForKey:#"sequence_nr"], [product objectForKey:#"name"]];
//word wrapping
productLabel.lineBreakMode = UILineBreakModeWordWrap;
productLabel.numberOfLines = 0; //infinite number of lines
productLabel.font = [UIFont fontWithName:#"Helvetica" size:14.0];
[cell.contentView addSubview:productLabel];
//create the cell's textfield
UITextField *cellTextField = [[UITextField alloc] initWithFrame:CGRectMake(cell.bounds.size.width - 50, cell.bounds.size.height - 30, 50, calculatedHeight - 20)];
cellTextField.adjustsFontSizeToFitWidth = YES;
cellTextField.textColor = [UIColor blackColor];
cellTextField.keyboardType = UIKeyboardTypeNumberPad; // will only need to end a count
cellTextField.returnKeyType = UIReturnKeyDone; // TODO make it go to the next items key, or make it exit out
cellTextField.backgroundColor = [UIColor whiteColor];
cellTextField.textAlignment = UITextAlignmentLeft; //align to the right
//cellTextField.delegate = self; //will need to set delegate, maybe
cellTextField.clearButtonMode = UITextFieldViewModeNever;
cellTextField.enabled = YES;
cellTextField.borderStyle = UITextBorderStyleRoundedRect; //add bezel rounded look to textfield
cellTextField.delegate = self;
[cell.contentView addSubview: cellTextField]; //add the textfield to the cell
return cell;
}
Either don't use reusability and always alloc the cell at each time or
make a check after dequeue (like this)
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell==nil)
{
// make text field and label an add tag
}
//and outside this by using tag fetch the labels and textField and clear the textFields.
You forgot to put the condition like this:
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:CellIdentifier];
}
Used this as a reference: add subviews to UITableViewCell
I just first checked to see if this view was added from before, and if it was, then don't add it again. It has nothing to do with the cell being nil. Unless I missed something? all I know is that this seems to be working fine, now.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"ProductCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSDictionary *product = [self.products objectAtIndex:indexPath.row];
NSDictionary *orderpoint = [self.orderpoints objectAtIndex:indexPath.row];
cell.textLabel.text = #""; //black out text
CGFloat calculatedHeight = [self tableView:tableView heightForRowAtIndexPath:indexPath];
UILabel *productLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, cell.bounds.size.width - 50.0, calculatedHeight)];
productLabel.text = [[NSString alloc] initWithFormat:#"%#. %#",
[orderpoint objectForKey:#"sequence_nr"], [product objectForKey:#"name"]];
//word wrapping
productLabel.lineBreakMode = UILineBreakModeWordWrap;
productLabel.numberOfLines = 0; //infinite number of lines
productLabel.font = [UIFont fontWithName:#"Helvetica" size:14.0];
[cell.contentView addSubview:productLabel];
if (![cell viewWithTag:1])
{
//create the cell's textfield
UITextField *cellTextField = [[UITextField alloc] initWithFrame:CGRectMake(cell.bounds.size.width - 50, cell.bounds.size.height - 30, 50, calculatedHeight - 20)];
cellTextField.adjustsFontSizeToFitWidth = YES;
cellTextField.textColor = [UIColor blackColor];
cellTextField.keyboardType = UIKeyboardTypeNumberPad; // will only need to end a count
cellTextField.returnKeyType = UIReturnKeyDone; // TODO make it go to the next items key, or make it exit out
cellTextField.backgroundColor = [UIColor whiteColor];
cellTextField.textAlignment = UITextAlignmentLeft; //align to the right
cellTextField.delegate = self; //will need to set delegate, maybe
cellTextField.clearButtonMode = UITextFieldViewModeNever;
cellTextField.enabled = YES;
cellTextField.borderStyle = UITextBorderStyleRoundedRect; //add bezel rounded look to textfield
cellTextField.delegate = self;
cellTextField.tag = 1; //set tag to 1
[cell.contentView addSubview: cellTextField]; //add the textfield to the cell
// save to dictionary, using a dictionary because not certain if this is created in order to use an Array
[self.textFieldDict setObject:cellTextField forKey:[[NSNumber alloc] initWithInteger:indexPath.row]];
}
return cell;
}
I have a big problem with an UITableView, I want to use a label inside the cell, so I use this method for do it
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"ItemCell";
// If the indexPath is less than the numberOfItemsToDisplay, configure and return a normal cell,
// otherwise, replace it with a button cell.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
else {
}
if (indexPath.section == 0) {
elemento = [array objectAtIndex:indexPath.row];
UILabel *labelTitle = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 220, 30)];
labelTitle.text = [elemento objectForKey:#"Titolo"];
labelTitle.backgroundColor = [UIColor clearColor];
labelTitle.textColor = [UIColor whiteColor];
[cell addSubview:labelTitle];
} else {
UILabel *labelTitle = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 220, 30)];
labelTitle.text = #"Read More";
labelTitle.backgroundColor = [UIColor clearColor];
labelTitle.textColor = [UIColor whiteColor];
[cell addSubview:labelTitle];
}
return cell;
}
in this way I can see all the data on my table, but the label are overlap, than I try to use this method
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"ItemCell";
// If the indexPath is less than the numberOfItemsToDisplay, configure and return a normal cell,
// otherwise, replace it with a button cell.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
if (indexPath.section == 0) {
elemento = [array objectAtIndex:indexPath.row];
UILabel *labelTitle = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 220, 30)];
labelTitle.text = [elemento objectForKey:#"Titolo"];
labelTitle.backgroundColor = [UIColor clearColor];
labelTitle.textColor = [UIColor whiteColor];
[cell addSubview:labelTitle];
} else {
UILabel *labelTitle = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 220, 30)];
labelTitle.text = #"Read More";
labelTitle.backgroundColor = [UIColor clearColor];
labelTitle.textColor = [UIColor whiteColor];
[cell addSubview:labelTitle];
}
}
else {
}
return cell;
}
the label are OK but in this case I can see on my table only 5 data, and this 5 data are repeat for some time...
For example if in the first case on my table I can see: 1,2,3,4,5,6,7,8,9,10,...
in the second case I seee: 1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,...
where is the problem?
add this code
for (UIView *view in [cell.contentView subviews])
{
[view removeFromSuperview];
}
before
if (indexPath.section == 0) {
elemento = [array objectAtIndex:indexPath.row];
UILabel *labelTitle = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 220, 30)];
labelTitle.text = [elemento objectForKey:#"Titolo"];
labelTitle.backgroundColor = [UIColor clearColor];
labelTitle.textColor = [UIColor whiteColor];
[cell addSubview:labelTitle];
Currently you add a label to the cell and the next time the cell is reused..the label is still there and you add a label on top of it.
The code you posted is specifying UITableViewCellStyleSubtitle as the cell style, which means each cell will a text label and detail text label available in its corresponding properties textLabel, and detailTextLabel. So there's no reason for you to allocate additional instances of UILabel. Instead, just populate the text properties of the existing labels. For example, you could rewrite your implementation like this:
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellID = #"ItemCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellID];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellID];
cell.textLabel.backgroundColor = [UIColor clearColor];
cell.textLabel.textColor = [UIColor whiteColor];
}
cell.textLabel.text = (indexPath.section == 0 ?
[array objectAtIndex:indexPath.row] :
#"ReadMore");
return cell;
}
I have used Cell.ContentView in my implementation for customizing the cell contents. It works fine but the only problem is when I have many cells and I scroll them up and down, the cell contents gets overwritten into the cells just become hidden followed by visible. Suppose I scroll first cell up and then again takes it down, the last cell's contents gets overwritten on first cell!!
I debugged enough on this but couldn't find the exact solution. I tried checking Cell.ContentView.SubViews count and if it 0 then only add other subviews. This doesn't display any cell contents until I scroll them up and down but once contents appeared, it doesn't overwrite..Little bit strange..!! I also made sure that I am using reusing the cell correctly. Following is my code that adds subviews into cell's contentview. Please let me know how could I get rid of this issue.
P.S: Don't worry about the variables and calculations I have done. Assume that it returns correct values. :)
- (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];
}
NSInteger totalAvailableSpace = IPHONE_DISPLAY_WIDTH - iconSize - accesorySize - 10;
NSInteger lableHeight = [[cellDetails objectForKey:#"TableItemTextFontSize"] intValue] * 2 + 10;
UILabel *textLabel = nil;
textLabel = [[[UILabel alloc] initWithFrame:CGRectMake(iconSize+12, self.tableCellHeight/2 - lableHeight/2, totalAvailableSpace * 0.8, lableHeight)] autorelease];
textLabel.numberOfLines = 2;
textLabel.lineBreakMode = UILineBreakModeWordWrap;
textLabel.textAlignment = UITextAlignmentLeft;
textLabel.text = [cellDetails objectForKey:#"TableItemMainText"];
if ([textLableColor scanHexInt:&hex]) {
textLabel.textColor = UIColorFromRGB(hex);
}
textLabel.font = [UIFont fontWithName:[cellDetails objectForKey:#"TableItemTextFontName"] size:[[cellDetails objectForKey:#"TableItemTextFontSize"] intValue]];
[cell.contentView addSubview:textLabel];
textLabel.backgroundColor = [UIColor clearColor];
lableHeight = [[cellDetails objectForKey:#"TableItemDetailTextFontSize"] intValue] * 2 + 10;
UILabel *detailTextLabel = nil;
detailTextLabel = [[[UILabel alloc] initWithFrame:CGRectMake(iconSize+10+totalAvailableSpace * 0.8+5, self.tableCellHeight/2 - lableHeight/2, totalAvailableSpace * 0.2 - 10, lableHeight)] autorelease];
detailTextLabel.numberOfLines = 2;
detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;
detailTextLabel.textAlignment = UITextAlignmentLeft;
detailTextLabel.text = [cellDetails objectForKey:#"TableItemDetailText"];
if ([detailTextLableColor scanHexInt:&hex]) {
detailTextLabel.textColor = UIColorFromRGB(hex);
}
detailTextLabel.font = [UIFont fontWithName:[cellDetails objectForKey:#"TableItemDetailTextFontName"] size:[[cellDetails objectForKey:#"TableItemDetailTextFontSize"] intValue]];
[cell.contentView addSubview:detailTextLabel];
detailTextLabel.backgroundColor = [UIColor clearColor];
return cell;
}
Thanks.
That is because toy are adding the views to your cell over and over again.
You should only add them when you create the cell and just set the labels when the cell is being reused.
You could set tags for your label, so that you can set it texts afterwards. The code bellow does the trick
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
if(style == UITableViewCellStyleValue1)
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
else
cell = [[[UITableViewCell alloc] initWithStyle:style reuseIdentifier:CellIdentifier] autorelease];
NSInteger totalAvailableSpace = IPHONE_DISPLAY_WIDTH - iconSize - accesorySize - 10;
NSInteger lableHeight = [[cellDetails objectForKey:#"TableItemTextFontSize"] intValue] * 2 + 10;
UILabel *textLabel = nil;
textLabel.tag = 1;
textLabel = [[[UILabel alloc] initWithFrame:CGRectMake(iconSize+12, self.tableCellHeight/2 - lableHeight/2, totalAvailableSpace * 0.8, lableHeight)] autorelease];
textLabel.numberOfLines = 2;
textLabel.lineBreakMode = UILineBreakModeWordWrap;
textLabel.textAlignment = UITextAlignmentLeft;
textLabel.text = [cellDetails objectForKey:#"TableItemMainText"];
if ([textLableColor scanHexInt:&hex]) {
textLabel.textColor = UIColorFromRGB(hex);
}
textLabel.font = [UIFont fontWithName:[cellDetails objectForKey:#"TableItemTextFontName"] size:[[cellDetails objectForKey:#"TableItemTextFontSize"] intValue]];
[cell.contentView addSubview:textLabel];
textLabel.backgroundColor = [UIColor clearColor];
lableHeight = [[cellDetails objectForKey:#"TableItemDetailTextFontSize"] intValue] * 2 + 10;
UILabel *detailTextLabel = nil;
detailTextLabel.tag = 2;
detailTextLabel = [[[UILabel alloc] initWithFrame:CGRectMake(iconSize+10+totalAvailableSpace * 0.8+5, self.tableCellHeight/2 - lableHeight/2, totalAvailableSpace * 0.2 - 10, lableHeight)] autorelease];
detailTextLabel.numberOfLines = 2;
detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;
detailTextLabel.textAlignment = UITextAlignmentLeft;
detailTextLabel.text = [cellDetails objectForKey:#"TableItemDetailText"];
if ([detailTextLableColor scanHexInt:&hex]) {
detailTextLabel.textColor = UIColorFromRGB(hex);
}
detailTextLabel.font = [UIFont fontWithName:[cellDetails objectForKey:#"TableItemDetailTextFontName"] size:[[cellDetails objectForKey:#"TableItemDetailTextFontSize"] intValue]];
[cell.contentView addSubview:detailTextLabel];
detailTextLabel.backgroundColor = [UIColor clearColor];
} else {
UILabel *textLabel = (UILabel *)[cell viewWithTag:1];
textLabel.text = [cellDetails objectForKey:#"TableItemMainText"];
UILabel *detailTextLabel = (UILabel *)[cell viewWithTag:2];
detailTextLabel.text = [cellDetails objectForKey:#"TableItemDetailText"];
}
return cell;
}
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease];
}
Make sure that dequeueReusableCellWithIdentifier and reuseIdentifier should be nil
Now it will work !!
Place all the cell UI content inside if(cell==nil){uilabel,uilabel or anythingUI related} ...since ui should be call only once at time of creating cel
To be clear, your problem is that as you scroll a cell into view you will often wind up with the text of the new cell being written over the top of a cell that was just scrolled offscreen?
The problem is that dequeueReusableCellWithIdentifier: doesn't "clean up" the cell (it calls prepareForReuse, but that's it), so all your old subviews are still in place. If you are going to reuse cells, you shouldn't be recreating these subviews each time. Instead, just adjust the properties of the existing subviews on a cell you get back from dequeueReusableCellWithIdentifier:, and only create the new subviews on a newly-allocated cell. Subclassing UITableViewCell can help with this, both to provide properties/ivars in which to hold references to these subviews and to organize the code a little nicer by moving the creation of subviews and the updating into appropriate methods. Or you could just not reuse cells, by passing nil for the reuse identifier.
The most likely reason that it didn't display any content until you scroll up and down is that a newly-created cell may have the framework-provided text field and image view, which may then be removed if the framework determines that you aren't actually using them.
In iOS5 UILineBreakModeWordWrap is deprecated. You should use NSLineBreakByWordWrapping instead.
This would change you code to look like detailTextLabel.lineBreakMode = NSLineBreakByWordWrapping and textLabel.lineBreakMode = NSLineBreakByWordWrapping.
I put multiple UILabels inside every cell in a UITableView instead of a single cell.textLabel.text. I then use reloaddata to put new uilabels. How do i get rid of the old labels ?
edit: If i put 5 labels in a cell then reload the cell using only 2 labels, there are 3 more labels left over from the last time i called cellForRowAtIndexPath.
If i use viewWithTag like Goldeen said, i can reuse old labels but can i remove labels i dont want from memory ?
edit:
this is my method
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
MyTableCell *cell = (MyTableCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[MyTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(j*50.0, 0, 49.0,logicTable.rowHeight)] autorelease];
label.tag = 1;
label.text = [NSString stringWithFormat:#"ABC"];
label.textAlignment = UITextAlignmentCenter;
label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:label];
return cell;
}
What it sounds like you are doing is, in your cellForRowAtIndexPath method, you are setting up your UITableViewCells with some labels in them and each time, you are making the labels from scratch. What you should be doing is, setting up the labels if you are making a new cell, and then setting the values on the labels outside of this to fully utilize the ability to reuse table view cells to improve performance of scrolling the table view.
The key method is -viewWithTag: which, along with the tag property on UIView you can use to find a specific subview.
A little sample code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"MyCellIdentifier";
UITableViewCell *cell = (WHArticleTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UILabel *firstLabel = nil;
UILabel *secondLabel = nil;
UILabel *thirdLabel = nil;
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
firstLabel = [[[UILabel alloc] initWithFrame: CGRectMake(0.0, 0.0, 20.0, 20.0)] autorelease];
firstLabel.tag = 1;
[cell addSubview:firstLabel];
secondLabel = [[[UILabel alloc] initWithFrame: CGRectMake(20.0, 0.0, 20.0, 20.0)] autorelease];
secondLabel.tag = 2;
[cell addSubview:secondLabel];
thirdLabel = [[[UILabel alloc] initWithFrame: CGRectMake(40.0, 0.0, 20.0, 20.0)] autorelease];
thirdLabel.tag = 3;
[cell addSubview:thirdLabel];
}
else
{
firstLabel = (UILabel *)[cell viewWithTag:1];
secondLabel = (UILabel *)[cell viewWithTag:2];
thirdLabel = (UILabel *)[cell viewWithTag:3];
}
firstLabel.text = #"First Label's Text Here";
secondLabel.text = #"Second Label's Text Here";
thirdLabel.text = #"Third Label's Text Here";
return cell;
}
I have a scrollable table.
In each cell I draw 3 UILabels. The first few cells draw ok. But as I scroll down the table the UILabels seems to be drawing over previous UILabels. Its like the Labels in the cell have an old label already there that was cleared. I could probably fix this by drawing a background color over the whole cell each redraw, but that still doesn't explain this strange problem and why its happening.
Anybody know why this occurs and what a solution might be?
- (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];
}
Match *aMatch = [appDelegate.matchScoresArray objectAtIndex:indexPath.row];
UILabel * teamName1Label = [[UILabel alloc]initWithFrame:CGRectMake(5,5, 100, 20)];
teamName1Label.textAlignment = UITextAlignmentCenter;
teamName1Label.textColor = [UIColor redColor];
teamName1Label.backgroundColor = [UIColor clearColor];
teamName1Label.text = aMatch.teamName1;
[cell addSubview:teamName1Label];
UILabel *teamVersusLabel = [[UILabel alloc]initWithFrame:CGRectMake(115,5, 40, 20)];
teamVersusLabel.textAlignment = UITextAlignmentCenter;
teamVersusLabel.textColor = [UIColor redColor];
teamVersusLabel.backgroundColor = [UIColor clearColor];
teamVersusLabel.text = #"V";
[cell addSubview:teamVersusLabel];
UILabel *teamName2Label = [[UILabel alloc]initWithFrame:CGRectMake(155,5, 100, 20)];
teamName2Label.textAlignment = UITextAlignmentCenter;
teamName2Label.textColor = [UIColor redColor];
teamName2Label.backgroundColor = [UIColor clearColor];
teamName2Label.text = aMatch.teamName2;
[cell addSubview:teamName2Label];
return cell;
}
Many Thanks
-Code
I think the best solution for this problem is to define these labels in the
-(UITableViewCell *)reuseTableViewCellWithIdentifier:(NSString *)identifier withIndexPath:(NSIndexPath *)indexPath method
-(UITableViewCell *)reuseTableViewCellWithIdentifier:(NSString *)identifier withIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell =[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier]autorelease];
UILabel * teamName1Label = [[UILabel alloc]initWithFrame:CGRectMake(5,5, 100, 20)];
teamName1Label.textAlignment = UITextAlignmentCenter;
teamName1Label.textColor = [UIColor redColor];
teamName1Label.backgroundColor = [UIColor clearColor];
teamName1Label.text = aMatch.teamName1;
teamName1Label.tag = 1;
[cell.contentView addSubview:teamName1Label];
[teamName1Label release];
UILabel *teamVersusLabel = [[UILabel alloc]initWithFrame:CGRectMake(115,5, 40, 20)];
teamVersusLabel.textAlignment = UITextAlignmentCenter;
teamVersusLabel.textColor = [UIColor redColor];
teamVersusLabel.backgroundColor = [UIColor clearColor];
teamVersusLabel.text = #"V";
teamVersusLabel.tag = 2;
[cell.contentView addSubview:teamVersusLabel];
[teamVersusLabel release];
UILabel *teamName2Label = [[UILabel alloc]initWithFrame:CGRectMake(155,5, 100, 20)];
teamName2Label.textAlignment = UITextAlignmentCenter;
teamName2Label.textColor = [UIColor redColor];
teamName2Label.backgroundColor = [UIColor clearColor];
teamName2Label.text = aMatch.teamName2;
teamName2Label.tag = 3;
[cell.contentView addSubview:teamName2Label];
[teamName2Label release];
return cell;
}
Now the cellForRowAtIndexPath method will be--
- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell=nil;
static NSString *Identifier = #"Cell";
cell = [theTableView dequeueReusableCellWithIdentifier:Identifier];
if(cell == nil){
cell = [self reuseTableViewCellWithIdentifier:Identifier withIndexPath:indexPath];
}
Match *aMatch = [appDelegate.matchScoresArray objectAtIndex:indexPath.row];
UILabel *label = (UILabel *)[cell.contentView viewWithTag:1];
label.text = aMatch.teamName1;
label = (UILabel *)[cell.contentView viewWithTag:2];
label.text = #"V";
label = (UILabel *)[cell.contentView viewWithTag:3];
label.text = aMatch.teamName2;
return cell;
}
Just try this code..Hope it helps :)
This is a cell re-use issue. The code is adding the labels to the cell every time cellForRowAtIndexPath is called (even if cell is not nil).
When you scroll, a previous cell that already has the labels is loaded and then the code adds new labels over the old ones.
Only create and add the labels to the cell in the if (cell == nil) section. When creating the labels, set tags on the labels.
Then outside the if, retrieve the labels using their tag using viewWithTag and set their text.