我希望用户添加的项目数量如下:
-__+
如果用户添加他添加的项目+按钮并增加项目。所以我将textfield
添加到表格并添加两个按钮加号(+)和减号( - )。这是cellForRowAtIndexPath
中的代码:
if(isPlus){
countFruitQty++;
cell.txtQty.text = [NSString stringWithFormat:@"%i",countFruitQty];
}
else{
countFruitQty--;
if(countFruitQty > 0)
cell.txtQty.text = [NSString stringWithFormat:@"%i",countFruitQty];
else{
cell.txtQty.text = @"";
countFruitQty = 0;
}
但是在滚动时,它会将数据更改为所有添加的textField。 如何防止这种情况?
答案 0 :(得分:3)
你必须为它管理数组,
检查以下代码供您参考,希望它能帮到您
@interface YourViewController ()
{
NSMutableArray *arrMain; // Your main array (Table row count)
NSMutableArray *arrCounter; // Counter array
int a;
}
- (void)viewDidLoad {
arrMain = [[NSMutableArray alloc] init];
arrCounter = [[NSMutableArray alloc] init];
a = 0;
for (int i = 0, i < [arrMain count], i++) {
[arrCounter addObject:[NSString stringWithFormat:@"%d",a]];
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
cell.btnPlus.tag = indexPath.row;
[cell.btnPlus addTarget:self action:@selector(click_Plus:) forControlEvents:UIControlEventTouchUpInside];
cell.btnMinus.tag = indexPath.row;
[cell.btnMinus addTarget:self action:@selector(click_Minus:) forControlEvents:UIControlEventTouchUpInside];
cell.txtQty.text = [arrCounter objectAtIndex:indexPath.row];
}
-(IBAction)click_Plus:(UIButton *)sender {
int qnt = [cell.txtQty.text intValue];
cell. txtQty.text = [NSString stringWithFormat:@"%d",++qnt];
[arrCounter replaceObjectAtIndex:sender.tag withObject:cell.txtQty.text];
}
-(IBAction)click_Minus:(UIButton *)sender {
int qnt = [cell.txtQty.text intValue];
cell.txtQty.text = [NSString stringWithFormat:@"%d",--qnt];
[arrCounter replaceObjectAtIndex:sender.tag withObject:cell.txtQty.text];
}
答案 1 :(得分:0)
这种情况会发生,因为当您滚动表格视图时,会重复使用并重置所有文本字段
如果你想要实现这个功能,你应该在需要时使用scrollview和addSuview