【发布时间】:2011-11-29 01:16:45
【问题描述】:
我有一个 UITableView,并以编程方式向单元格添加两个按钮。 1 个按钮添加到单元格文本(向上计数),另一个减去 1(向下计数)。但是,假设我添加 4,单元格的文本将是 4,但是当我向上滚动该单元格并移出视图时,当它回到视图中时,单元格文本又回到 1,这就是它开始了。如果我在单元格文本中添加(如果我也减去它也一样)并切换页面然后返回表格视图,也会发生同样的情况。这是cellForRow:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
newBtn = [[UIButton alloc]init];
newBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[newBtn setFrame:CGRectMake(260,20,55,35)];
[newBtn addTarget:self action:@selector(subtractLabelText:) forControlEvents:UIControlEventTouchUpInside];
[newBtn setTitle:@"-" forState:UIControlStateNormal];
[newBtn setEnabled:YES];
[cell addSubview:newBtn];
subBtn = [[UIButton alloc]init];
subBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[subBtn setFrame:CGRectMake(200,20,55,35)];
[subBtn addTarget:self action:@selector(addLabelText:) forControlEvents:UIControlEventTouchUpInside];
[subBtn setTitle:@"+" forState:UIControlStateNormal];
[subBtn setEnabled:YES];
[cell addSubview:subBtn];
}
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
cell.imageView.image = [imageArray objectAtIndex:indexPath.row];
cell.textLabel.text = [cells objectAtIndex:indexPath.row];
return cell;
}
感谢您的任何帮助!谢谢:D
按钮方法
- (IBAction)addLabelText:(id)sender{
cell = (UITableViewCell*)[sender superview];
cell.textLabel.text = [NSString stringWithFormat:@"%d",[cell.textLabel.text intValue] +1];
}
- (IBAction)subtractLabelText:(id)sender
{
cell = (UITableViewCell*)[sender superview];
if ( [[cell.textLabel text] intValue] == 0){
cell.textLabel.text = [NSString stringWithFormat:@"%d",[cell.textLabel.text intValue] +0];
}
else{
cell.textLabel.text = [NSString stringWithFormat:@"%d",[cell.textLabel.text intValue] -1];
//[myTableView reloadData];
}
}
【问题讨论】:
-
那是因为单元格被重用了,你需要在 cellForRowAtIndexPath 中(重新)设置东西(标签、按钮),以确保在重用单元格时,单元格上的所有组件都是正确的。例如,如果您在单元格上有一个按钮,并且其文本逐行不同,则需要在 cellForRowAtIndexPath 中重置该文本;如果所有行的文本都相同,则显然没有什么可担心的。
-
非常感谢彼得的帮助!你如何建议我重置
cellForRowAtIndexPath中的单元格文本?非常感谢! :D
标签: iphone ios cocoa-touch uitableview