2015-02-18 4 views
3

Я хочу сделать вид вида, где у меня есть пользовательская ячейка, чтобы показать список элементов и кнопку для добавления и удаления элементов (+/-).Приращение, уменьшение на метке при нажатии кнопки + или - в ios

Когда я нажимаю кнопку «Добавить» или «Удалить», я хочу, чтобы она работала только для одной ячейки и увеличивала значение ячейки.

На данный момент он работает, но он увеличивает все в ячейке, как я могу управлять этим для каждой независимой ячейки?

- (UITableViewCell *)tableView:(UITableView *)tableView 
     cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    TableViewCell *cell = 
     (TableViewCell *)[_tableView dequeueReusableCellWithIdentifier:@"Cell"]; 
    cell.addButton.tag = indexPath.row; 
    cell.removeButton.tag = indexPath.row; 
    cell.itemName.text = [models objectAtIndex:indexPath.row]; 
    cell.itemPrice.text = [[stock objectAtIndex:indexPath.row] stringValue]; 
    cell.count = [NSNumber numberWithInt:i]; 
    cell.quantityLbl.text = [NSString stringWithFormat:@"%@", cell.count]; 
    cell.quantityLbl.layer.cornerRadius = YES; 
    cell.quantityLbl.layer.borderWidth = 1.0; 
    return cell; 
} 

На надстройке Баттона: -

- (IBAction)addButton:(id)sender { 
    NSInteger num = [sender tag]; 
    i = i + 1; 
    NSIndexPath *rowToReload = [NSIndexPath indexPathForRow:num inSection:0]; 
    NSArray *rowsToReload = [NSArray arrayWithObjects:rowToReload, nil]; 
    [_tableView reloadRowsAtIndexPaths:rowsToReload 
        withRowAnimation:UITableViewRowAnimationNone]; 
} 

enter image description here

ответ

4
-(IBAction)addButton:(id)sender{ 

TableViewCell *cell; 
// check device version 
if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")){ 
    cell = (TableViewCell*)((UIButton*)sender).superview.superview.superview; 
} 
else{ 
cell = (TableViewCell*)((UIButton*)sender).superview.superview.superview.superview; 
} 

    cell.lblNumber.text = [NSString stringWithFormat:@"%d",[cell.lblNumber.text intValue]+1]; 
} 

макро

#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending) 
+0

спасибо s работает ..... – RaviJSS

+0

мое удовольствие @RaviJSS – KDeogharkar

+0

@KDeogharkar было бы здорово иметь обновление Swift 2! – lukaivicev

1

Вам нужно сделать еще один массив, называемый «счетчик» или что-то, и инициализировать его, чтобы быть такой же длины, как ваши «модели ", у которого вначале есть несколько объектов NSNumber с целым значением 0.

Затем измените код кнопки добавления так, чтобы он выглядел следующим образом:

- (IBAction)addButton:(id)sender { 
    NSInteger num = [sender tag]; 
    int value = [count[num] integerValue]; 
    value += 1; 
    count[num] = @(value); 
    NSIndexPath *rowToReload = [NSIndexPath indexPathForRow:num inSection:0]; 
    NSArray *rowsToReload = [NSArray arrayWithObjects:rowToReload, nil]; 
    [_tableView reloadRowsAtIndexPaths:rowsToReload 
        withRowAnimation:UITableViewRowAnimationNone]; 
} 

И убедитесь, что вы обновить вашу функцию cellforrowatindexpath, а также:

- (UITableViewCell *)tableView:(UITableView *)tableView 
     cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    TableViewCell *cell = 
     (TableViewCell *)[_tableView dequeueReusableCellWithIdentifier:@"Cell"]; 
    cell.addButton.tag = indexPath.row; 
    cell.removeButton.tag = indexPath.row; 
    cell.itemName.text = [models objectAtIndex:indexPath.row]; 
    cell.itemPrice.text = [[stock objectAtIndex:indexPath.row] stringValue]; 
    cell.count = count[indexPath.row]; 
    cell.quantityLbl.text = [NSString stringWithFormat:@"%@", cell.count]; 
    cell.quantityLbl.layer.cornerRadius = YES; 
    cell.quantityLbl.layer.borderWidth = 1.0; 
    return cell; 
} 
0

Используйте это, если вы обновляете только одна ячейка: -

[NSArray arrayWithObject:rowToReload]; 

вместо: -

NSArray *rowsToReload = [NSArray arrayWithObjects:rowToReload, nil]; 
0

попробуйте

- (IBAction)addButton:(id)sender 
{ 
    NSInteger num = [sender tag]; 
    i = i + 1; 

    UIButton * button = (UIButton*)sender; 
    CGPoint buttonPosition = [button convertPoint:CGPointZero toView: _tableView]; 

    NSIndexPath *indexPathToReload = [_tableView indexPathForRowAtPoint:buttonPosition]; 
    NSArray *rowsToReload = [NSArray arrayWithObjects:indexPathToReload, nil]; 
    [_tableView reloadRowsAtIndexPaths:rowsToReload 
        withRowAnimation:UITableViewRowAnimationNone]; 
} 
0

Это совершенно другой код надеюсь, что это будет работать

in .h file 
NSMutableDictionary *counts; 
NSMutableArray *countarr1; 

in .m file 
- (void)viewDidLoad { 
    [super viewDidLoad]; 
counts=[[NSMutableDictionary alloc]initWithObjectsAndKeys:@"0",@"0",@"0",@"1",@"0",@"2",@"0",@"3", nil]; 

countarr1=[[NSMutableArray alloc]init]; 

} 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath; 
{ 
    static NSString *[email protected]"Id"; 
    TabletsListTableViewCell *cell=[tableview dequeueReusableCellWithIdentifier:str]; 
    if (cell==0) 
    { 
     cell=[[[NSBundle mainBundle]loadNibNamed:@"TabletsListTableViewCell" owner:0 options:nil]objectAtIndex:0]; 
    } 
cell.PlusBtn.tag=indexPath.row; 
cell.MinusBtn.tag=indexPath.row; 

//This is Label where you want to show quantity 
    cell.QuantityLbl.text=[NSString stringWithFormat:@"%@",[counts valueForKey:[NSString stringWithFormat:@"%ld",(long)indexPath.row]]]; 

//Add Action Method For Plus (+) And Minus (-) Button 
[cell.MinusBtn addTarget:self action:@selector(MinusButtonClicked:) forControlEvents:UIControlEventTouchUpInside]; 
[cell.PlusBtn addTarget:self action:@selector(PlusButtonClicked:) forControlEvents:UIControlEventTouchUpInside]; 

    return cell; 
} 

Write Method для (+) и (-) Кнопка

-(void)MinusButtonClicked:(UIButton*)sender 
{ 
    int sum=1; 
    if ([[counts valueForKey:[NSString stringWithFormat:@"%ld",(long)sender.tag]] integerValue] >0) { 
     sum=[[counts valueForKey:[NSString stringWithFormat:@"%ld",(long)sender.tag]] integerValue]; 
    } 
    sum=sum - 1; 
    [counts setObject:[NSString stringWithFormat:@"%d",sum] forKey:[NSString stringWithFormat:@"%ld",(long)sender.tag]]; 
    [self.tableview reloadData]; 
} 

-(void)PlusButtonClicked:(UIButton*)sender 
{ 
    int i=sender.tag; 
    int sum=0; 
    if ([[counts valueForKey:[NSString stringWithFormat:@"%ld",(long)sender.tag]] integerValue] >0) { 
     sum=[[counts valueForKey:[NSString stringWithFormat:@"%ld",(long)sender.tag]] integerValue]; 
    } 
    sum=sum + 1; 
    [counts setObject:[NSString stringWithFormat:@"%d",sum] forKey:[NSString stringWithFormat:@"%ld",(long)sender.tag]]; 
    [self.tableview reloadData]; 
} 
Смежные вопросы