2015-06-25 5 views
3

Я хочу что-то вроде изображения ниже. Пользователь может нажать кнопку + или - и увеличенное или уменьшенное количество отображается в UILabel i.e 1 на изображении ниже.
Я знаю, как реализовать пользовательскую ячейку представления таблицы. Я также знаю, как реализовать селектор. но мне нужно установить текст ярлыка в соответствии с нажатой кнопкой, вот только проблема. кнопку Как я могу обновить щелкнули и набора текст UILabel заказной клетку вне от cellForRowAtIndexPathwith особенностей добавить вычитать.Доступ к пользовательским атрибутам ячеек вне cellForRowAtIndexPath

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

    //self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone; 

    static NSString *simpleTableIdentifier = @"ProductListVIICell"; 

    ProductListVIICell *cell = (ProductListVIICell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier]; 

    if (cell == nil) 
    { 
     NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ProductListVIICell" owner:self options:nil]; 
     cell = [nib objectAtIndex:0]; 
    } .................................... 
     cell.btnMinus.tag = indexPath.row; 
     cell.btnPlus.tag = indexPath.row; 

     [cell.btnPlus addTarget:self action:@selector(addItem:) forControlEvents:UIControlEventTouchUpInside]; 
     [cell.btnMinus addTarget:self action:@selector(deleteItem:) forControlEvents:UIControlEventTouchUpInside]; 

     cell.lblCount.tag = [[NSString stringWithFormat:@"%d%d",addBtnClickCount,addBtnClickCount] integerValue]; 


     return cell; 
    } 

Мне нужно сделать что-то здесь, но не получило то, что я хочу достичь. cell.lblTitle.text разве работает

#pragma mark - UIButton selector 

-(void)addItem:(UIButton*)button { 
    itemCount++; 
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:button.tag inSection:1]; 
    ProductListVIICell *cell = (ProductListVIICell *)[self.tableView cellForRowAtIndexPath:indexPath]; 
     cell.lblCount.textColor = [UIColor redColor]; 
    cell.lblTitle.text = [NSString stringWithFormat:@"%d",itemCount]; 

    NSIndexPath* rowToReload = [NSIndexPath indexPathForRow:[button tag] inSection:0]; 
    NSArray* rowsToReload = [NSArray arrayWithObjects:rowToReload, nil]; 
    [self.tableView reloadRowsAtIndexPaths:rowsToReload withRowAnimation:UITableViewRowAnimationNone]; 
    NSLog(@"%d",itemCount); 
    [self.tableView reloadData]; 


} 

-(void)deleteItem:(UIButton*)button { 
    itemCount--; 
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:button.tag inSection:1]; 
    ProductListVIICell *cell = (ProductListVIICell *)[self.tableView cellForRowAtIndexPath:indexPath]; 

    cell.lblCount.textColor = [UIColor redColor]; 
    cell.lblTitle.text = [NSString stringWithFormat:@"%d",itemCount]; 

    NSIndexPath* rowToReload = [NSIndexPath indexPathForRow:[button tag] inSection:0]; 
    NSArray* rowsToReload = [NSArray arrayWithObjects:rowToReload, nil]; 
    [self.tableView reloadRowsAtIndexPaths:rowsToReload withRowAnimation:UITableViewRowAnimationNone]; 
    NSLog(@"%d",itemCount); 
    [self.tableView reloadData]; 

} 

enter image description here

Эти ссылки могут быть использованы слишком

Accessing cell attributes outside of cellForRowAtIndexPath

http://code.tutsplus.com/tutorials/blocks-and-table-view-cells-on-ios--mobile-22982 , но это только для UITableViewCell не пользовательской ячейке

я был в состоянии решить мою проблему с помощью следующего

@interface ProductListVC() 
{ 
    int count; 
    bool addBtnClicked; 
    bool minusBtnClicked; 


} 

@property (strong,nonatomic) NSMutableArray* quantityArray; //stores label 
@property (strong,nonatomic) NSMutableArray* quantityLabelArray; //stores label 

- (void)viewDidLoad { 

    [super viewDidLoad]; 

    _quantityLabelArray = [[NSMutableArray alloc] init]; 
    _quantityArray = [[NSMutableArray alloc] init]; 

//determine num of row prevent index 2 beyond bounds for empty array error i.e insert straight to let's say index 3 
    for (int i=0; i <=[_productArray count]; i++) { 
      [_quantityArray addObject:@"0"]; 

     } 
} 


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

if (!_quantityArray || !_quantityArray.count){ 
     cell.lblCount.text = [NSString stringWithFormat:@"%d", 0]; 

    }else{ 
     cell.lblCount.text = [_quantityArray objectAtIndex:indexPath.row]; 
    } 
    [_quantityLabelArray addObject:cell.lblCount]; 


    if (addBtnClicked || minusBtnClicked) { 
     //If add or minu button is reloading the cell 

     cell.lblCount.text = [_quantityArray objectAtIndex:indexPath.row]; 
     //NSLog(@"%@",cell.lblCount.text); 
     [_quantityLabelArray replaceObjectAtIndex:indexPath.row withObject:cell.lblCount]; 
     addBtnClicked = NO; 
     minusBtnClicked = NO; 

    } 
    else 
    { 

    } 

    cell.btnMinus.tag = indexPath.row; 
    cell.btnPlus.tag = indexPath.row; 
    cell.lblCount.tag = indexPath.row; 

    [cell.btnPlus addTarget:self action:@selector(addItem:) forControlEvents:UIControlEventTouchUpInside]; 
    [cell.btnMinus addTarget:self action:@selector(deleteItem:) forControlEvents:UIControlEventTouchUpInside]; 

    cell.selectionStyle = UITableViewCellSelectionStyleNone; 
    return cell; 
} 



#pragma mark - UIButton selector 

-(void)addItem:(UIButton*)button 

{ 

    NSLog(@"btn tag %ld",(long)[button tag]); 
    NSLog(@"quantitylblarry %@",_quantityLabelArray); 

     UILabel* lblShowCount = [_quantityLabelArray objectAtIndex:[button tag]]; 
     if ([lblShowCount.text integerValue]< 10) { 
      count = count+1; 
      lblShowCount.text = [NSString stringWithFormat:@"%ld", [lblShowCount.text integerValue]+1]; 
     } 

    NSLog(@"quantity array count %lu",(unsigned long)_quantityArray.count); 

     if (_quantityArray.count > [button tag]) { 

      [_quantityArray removeObjectAtIndex:[button tag]]; 
      [_quantityArray insertObject:lblShowCount.text atIndex:[button tag]]; 
     } 

     else{ 

      [_quantityArray insertObject:lblShowCount.text atIndex:[button tag]]; 
     } 
     addBtnClicked = YES; 

     NSLog(@"quantity array %@",_quantityArray); 
     NSIndexPath* rowToReload = [NSIndexPath indexPathForRow:[button tag] inSection:0]; 
     NSArray* rowsToReload = [NSArray arrayWithObjects:rowToReload, nil]; 
     [self.tableView reloadRowsAtIndexPaths:rowsToReload withRowAnimation:UITableViewRowAnimationNone]; 

    } 





-(void)deleteItem:(UIButton*)button{ 

    NSLog(@"%ld",(long)[button tag]); 
    UILabel* lblShowCount = [_quantityLabelArray objectAtIndex:[button tag]]; 


     if ([lblShowCount.text integerValue]>=1) { 
      count = count-1; 
      lblShowCount.text = [NSString stringWithFormat:@"%ld", [lblShowCount.text integerValue]-1]; 

     } 

     NSLog(@"%lu",(unsigned long)_quantityArray.count); 

     if (_quantityArray.count > [button tag]) { 
      [_quantityArray removeObjectAtIndex:[button tag]]; 
      [_quantityArray insertObject:lblShowCount.text atIndex:[button tag]]; 
     } 
     else{ 
      [_quantityArray insertObject:lblShowCount.text atIndex:[button tag]]; 

     } 
     NSLog(@"%@",_quantityArray); 
     minusBtnClicked =YES; 

     NSLog(@"quantity array %@",_quantityArray); 
     NSIndexPath* rowToReload = [NSIndexPath indexPathForRow:[button tag] inSection:0]; 
     NSArray* rowsToReload = [NSArray arrayWithObjects:rowToReload, nil]; 
     [self.tableView reloadRowsAtIndexPaths:rowsToReload withRowAnimation:UITableViewRowAnimationNone]; 

} 
+0

вы должны увидеть это http://stackoverflow.com/questions/15652133/how-to-set-action-for-uibutton-in-uitableviewcell ..i сделали это быстро, но не в объективе c ... –

+0

Я знаю, что действие для UIButton в UITable ViewCell, но проблема заключается в установке UILabel каждый раз, когда пользователь нажимает кнопку –

+0

cell.lblTitle.text = "value changed"; это работает? Все, что вы делаете, кажется правильным –

ответ

2

это лучше использовать пользовательскую ячейку. Проверьте это tutorials или это one, то вам нужно будет добавить делегата в эту камеру, так что вы можете синхронизировать количества с вами ViewController

т.е.

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    CustomTableViewCell *cell = (CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"CustomTableViewCell" forIndexPath:indexPath]; 
    cell.delegate = self; 
    cell.itemIndex = indexPath.row; 
    .... 
    return cell 
} 

UPDATE

, если у вас есть обычай ячейку, вы должны добавить выход и изменить его текст в действии кнопок +/-, весь этот код будет в CustomTableViewCell.m

-(void)addItem:(UIButton*)button {  
    self.itemQuantity++; 
    [self updateQuantity]; 
} 

-(void)deleteItem:(UIButton*)button { 
    self.itemQuantity--; 
    [self updateQuantity]; 
} 
- (void)updateQuantity{ 
    self.lblCount.text = [NSStirng stringWithFormat:@"%d", self.itemQuantity]; 
    [self.delegate updateItemAtIndex:self.itemIndex withQuantity:self.itemQuantity]; 
} 

UPDATE: КОМПЛЕКСНОЕ РЕШЕНИЕ

1. Модель

@interface Item : NSObject 
@property (nonatomic, strong) NSString *title; 
@property (nonatomic) NSInteger quantity; 
@end 

@implementation Item 

@end 

2. Пользовательские сотовый

@interface CustomItemTableViewCell : UITableViewCell 

@property (nonatomic, weak) IBOutlet UILabel *lblTitle; 
@property (nonatomic, weak) IBOutlet UILabel *lblCount; 
@property (nonatomic, assign) Item *item; 
@end 

@implementation CustomItemTableViewCell 

- (void)updateCellWithItem:(Item *)item { 
    self.item = item; 
    [self updateCellView]; 
} 
- (void)updateCellView { 
    self.lblTitle.text = self.item.title; 
    self.lblTitle.text = [NSString stringWithFormat:@"%ld", self.item.quantity]; 
} 
- (IBAction)addItem:(UIButton*)button { 
    self.item.quantity++; 
    [self updateCellView]; 
} 

- (IBAction)deleteItem:(UIButton*)button { 
    self.item.quantity--; 
    [self updateCellView]; 
} 

@end 

3. TableViewController

@interface ItemsTableViewController : UITableViewController 
@property (nonatomic, strong) NSArray *items; 
@end 

@implementation ItemsTableViewController 

#pragma mark - Table view data source 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return self.items.count; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    CustomItemTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomItemCell" forIndexPath:indexPath]; 

    [cell updateCellWithItem:self.items[indexPath.row]]; 

    return cell; 
} 
+1

Я знаю, как реализовать пользовательскую таблицу представления таблицы. Можете снова проверить вопрос. Я знаю, как реализовать селектор тоже. но мне нужно увеличивать и уменьшать текст ярлыка в соответствии с нажатой кнопкой мыши. Это только проблема –

+0

, если у вас есть пользовательская ячейка, вы должны добавить выход 'UILabel' и изменить его текст в действии кнопок' +/- ' , весь этот код будет в 'CustomTableViewCell.m' –

+0

, который уже сделан. можно снова прочитать вопрос –

0

Чтобы изменить текст метки ячейки вам необходимо извлечь объект клеток в этих селекторов, которые вы можете сделать, просто используя параметр отправителя, в вашем случае кнопку. См. Код ниже для добавления функциональности.

-(void)addItem:(UIButton*) button 
{  
    NSLog(@"UIButton%ld",(long)button.tag); 
    addBtnClickCount++; //Increase the count by 1 
    MyCustomCell *cell = button.superview.superview; 
    //Now change the label text for cell 
    cell.lblCount.text = [NSString stringWithFormat:@"%d",addBtnClickCount]; 
} 

То же самое, что вы можете сделать для вычитания функциональности.

+0

do u действительно думаю, что это можно сделать cell.lblCount.text за пределами cellForRowAtIndexPath –

+0

Я не пробовал это сам. Но это должно быть, поскольку вы просто модифицируете объект ячейки. Просто попробуйте один раз. – Gandalf

+0

можно проверить мои измененные вопросы –

0

Использование более крутого элемента управления в пользовательской ячейке таблицы.

this is my screen.i used stepper control and label.

customcell.h класс

@property (weak, nonatomic) IBOutlet UIStepper *stepper; 
@property (weak, nonatomic) IBOutlet UILabel *lbl_value; 

**** customcell.m ****

- (IBAction)stepper:(UIStepper *)sender { 
    NSUInteger value = sender.value; 
    lbl_value.text = [NSString stringWithFormat:@"%03d",value]; 
    self.txt1.text= [NSString stringWithFormat:@"%03d",value]; 

} 
Смежные вопросы