我有一個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 – iProRage