Reputation: 69
I want number of item to add by user like :
-__+
If user add item that he add + button and increase item. so i added textfield
to table and add two button Plus(+) and Minus(-). Here is my code in 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;
}
But on scroll it change data to all added textField. How to Prevent this?
Upvotes: 1
Views: 803
Reputation: 2268
You have to manage array for it,
Check below code for your reference, Hope it will help you out
@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];
}
Upvotes: 3
Reputation: 16456
this happens because when you scroll your tableview cell is reused and reset all your textfield
if you want to achieve this functionality you should use scrollview and addSuview when you need
Upvotes: 0