Hello , i have a strange issue with my UITableView...I add a UIButton as a subview to each cell , but when any of the cells gets out of view something happens, and when i scroll up again , i can see that the UIButton background images of some cells are overlapping !
The cellForRowAtIndexPath method i use contains the following code , which adds the uibutton instances
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell"];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:@"MyCell"];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
UIFont *titleFont = [UIFont fontWithName:@"Arial-BoldMT" size:14.0];
[[cell textLabel] setFont:titleFont];
[cell autorelease];
}
if([cell viewWithTag:indexPath.row]==nil){
UIButton *buttonLeft = [UIButton buttonWithType:UIButtonTypeCustom];
buttonLeft.tag=indexPath.row;
if ([[myArray objectAtIndex:indexPath.row] isEqualToString:@"item1"]) {
[buttonLeft addTarget:self action:@selector(doThat:) forControlEvents:UIControlEventTouchUpInside];
[buttonLeft setBackgroundImage:[UIImage imageNamed:@"item1.png"] forState:UIControlStateNormal];
[buttonLeft setFrame: CGRectMake( 5.0f, 6.2f, 30.0f, 30.0f)];
}else{
[buttonLeft addTarget:self action:@selector(doThat:) forControlEvents:UIControlEventTouchUpInside];
[buttonLeft setBackgroundImage:[UIImage imageNamed:@"item2.png"] forState:UIControlStateNormal];
[buttonLeft setFrame: CGRectMake( 5.0f, 6.2f, 30.0f, 30.0f)];
}
[cell addSubview:buttonLeft];
}
cell.textLabel.text=[NSString stringWithFormat:@" %@",[myArray objectAtIndex:indexPath.row]];
return cell;
}
Apparently , this code for some reason adds the UIButton everytime the cell is displayed. I want each button subview to be added only once.. What am i doing wrong ?
Your help is much appreciated