【发布时间】:2009-10-20 17:29:35
【问题描述】:
我在下面有这段代码来动态填充我的 UITableView。
我必须显示两种单元格:带有背景图像的常规单元格和带有常规背景图像的单元格,外加标签和按钮。
如果 Indexpath.row 小于控制变量,则绘制常规单元格。如果没有,则绘制带有按钮和标签的单元格。
这是代码
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = @"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:MyIdentifier] autorelease];
}
UIImage *imageU;
if (indexPath.row < controlVariable) {
imageU = [[[UIImage alloc]initWithContentsOfFile:[[NSBundle mainBundle]
pathForResource:[NSString stringWithFormat: @"table%d", indexPath.row] ofType:@"jpg"]] autorelease];
cell.imageView.image = imageU;
} else {
imageU = [[[UIImage alloc]initWithContentsOfFile:[[NSBundle mainBundle]
pathForResource:[NSString stringWithFormat: @"table-pg%d",numberX]
ofType:@"jpg"]] autorelease];
cell.imageView.image = imageU;
NSString * myString = [NSString stringWithFormat: @"pago%d", numberX];
UILabel * myLabel = [[UILabel alloc] initWithFrame:CGRectMake(5.0, 49.0, 200.0, 22.0)];
[myLabel setTextAlignment:UITextAlignmentLeft];
[myLabel setBackgroundColor:[UIColor blueColor]];
[myLabel setClipsToBounds:YES];
[myLabel setFont:[UIFont systemFontOfSize:14.0]];
[myLabel setTextColor:[UIColor blackColor]];
[myLabel setText: myString];
[myLabel setAlpha:0.6];
[cell addSubview: myLabel];
[myLabel release];
UIButton *buyButton = [[UIButton alloc] initWithFrame:CGRectMake( 220, 4, 100, 35)];
buyButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
buyButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
[buyButton setTitle:NSLocalizedString(@"buyKey", @"") forState:UIControlStateNormal];
[buyButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
buyButton.titleLabel.font = [UIFont boldSystemFontOfSize:14];
UIImage *newImage = [[[[UIImage alloc]initWithContentsOfFile:[[NSBundle mainBundle]
pathForResource: @"whiteButton" ofType:@"png"]] autorelease]
stretchableImageWithLeftCapWidth:12.0f topCapHeight:0.0f];
[buyButton setBackgroundImage:newImage forState:UIControlStateNormal];
[buyButton addTarget:self action:@selector(comprar:) forControlEvents:UIControlEventTouchDown];
buyButton.backgroundColor = [UIColor clearColor];
[buyButton setTag:indexPath.row];
[cell addSubview:buyButton];
[buyButton release];
}
return cell;
}
这段代码的问题是:当我向下滚动 UITableView 并到达常规单元格和带有按钮和标签的单元格之间的划分时,我看到它正在正确呈现,但是如果我在深入下去后向上,我会看到按钮和标签被添加到不应该有它们的单元格中。从现在开始,所有单元格都包含按钮和标签...
就像单元格在绘制之前没有释放其内容一样。就像标签和按钮被添加到单元格上已经存在的其他按钮和标签之上。单元格在再次绘制之前不会释放其内容。
如何解决?
感谢您的帮助。
注意:在进行两个第一个答案建议的更改后,我几乎看不到任何区别。现在,并不是所有的细胞都是错的,只是一些。每次我向下滚动表格并返回表格的开头时,它们都会改变。
【问题讨论】:
标签: iphone iphone-sdk-3.0