My goal is to display 2 strings in the same cell, one of them left aligned and the other right aligned. The code I have attached does just that in a table view, however it breaks when you scroll up/down. I need this to work in a table that can scroll. Someone had mentioned using CustomUITableViewCells instead of my current method, can anyone point me to an example of this?
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
UILabel *rank = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, 100, 20];
[rank setTag:5];
[cell.contentView addSubview:rank];
[rank release];
UILabel *item = [[UILabel alloc] initWithFrame:CGRectMake(110, 5, 220, 20];
[item setTextAlignment:UITextAlignmentRight];
[item setTag:6];
[cell.contentView addSubview:item];
[item release];
}
UILabel *rank = (UILabel *)[cell viewWithTag:5];
UILabel *item = (UILabel *)[cell viewWithTag:6];
rank.text = @"leftside";
item.text = @"rightside";
}
Any ideas and thoughts greatly appricated, thanks for lookin
This problem is because of
dequeueReusableCellWithIdentifier. While the cell is being re-used, and when you scroll up and down it will cause major problems as labels are being added as subviews to the cells and they do not have the properties of the cell. However, if you use thecell.textLabelas your label, it would not cause problems like the one you are facing now, but you cannot add more than one label.You have two solutions for this.
In your case, you need to stop using the same
cellIdentifierfor each and use different identifiers for each cells so that they do not get reused. This would be helpful if you have a very small number of rows in thetableViewor it would turn out to be inefficient.A better solution would be to subclass
UITableViewCelland add those two labels in it’s code, and then use that UITableViewCell withdequeueReusableCellWithIdentifier. This is just a small amount of work, and you get to re-use cells. This would be very helpful if you have a large number of rows in your tableview.Go through THIS TUTORIAL to learn on how to subclass
UITableViewCellwith 2 labels.You will need to work with the method,
- (void)layoutSubviewsand add those labels to your customUITableViewCellsubclass.And remember to reference this
customUITableViewCellinstead of the default uitableviewcell when you are loading up thetableView. YourUILabelswill not be messed up anymore.Another reference.