2016-02-02 2 views
0

Я новичок в разработчике ios.Json issue in tableview with stepper and lable

Я хочу, чтобы выбранные данные были в другой таблице, моя проблема в том, что я не знаю, как получить имя и количество.

Смотрите здесь мой снимок экрана

enter image description here

Мои данные JSON, как этот формат

{ 
     Data =  (
        { 
       "Dry_cleaning" = 49; 
       Iron = 8; 
       Name = "Shirt/Tees"; 
       Wash = 15; 
       "Wash_Iron" = 19; 
       id = 1; 
      }, 
        { 
       "Dry_cleaning" = 49; 
       Iron = 5; 
       Name = "Kurta(short)"; 
       Wash = 20; 
       "Wash_Iron" = 19; 
       id = 2; 
      }, 
        { 
       "Dry_cleaning" = 50; 
       Iron = 8; 
       Name = "Kurta(Long)"; 
       Wash = 15; 
       "Wash_Iron" = 20; 
       id = 3; 
      }, 
        { 
       "Dry_cleaning" = 50; 
       Iron = 5; 
       Name = Shorts; 
       Wash = 15; 
       "Wash_Iron" = 19; 
       id = 4; 
      }, 
        { 
       "Dry_cleaning" = 55; 
       Iron = 8; 
       Name = "Trousers/Pyjamas"; 
       Wash = 20; 
       "Wash_Iron" = 30; 
       id = 5; 
      }, 
        { 
       "Dry_cleaning" = 70; 
       Iron = 7; 
       Name = Jeans; 
       Wash = 20; 
       "Wash_Iron" = 29; 
       id = 6; 
      }, 
        { 
       "Dry_cleaning" = 150; 
       Iron = 5; 
       Name = Blazer; 
       Wash = 25; 
       "Wash_Iron" = 19; 
       id = 7; 
      }, 
        { 
       "Dry_cleaning" = 100; 
       Iron = 6; 
       Name = "Leather_Jacket"; 
       Wash = 30; 
       "Wash_Iron" = 36; 
       id = 8; 
      } 
} 

Вот это мой код

ViewController.h

импорт

@interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate> 

@property (weak, nonatomic) IBOutlet UITableView *tableview; 
@property (strong, nonatomic)NSMutableArray *arrayCounts; 
- (IBAction)placeorder:(id)sender; 
@end 

ViewController.m

// 
// ViewController.m 
// orderscreenfile 
// 
// Created by Tranetech on 02/02/16. 
// Copyright (c) 2016 Tranetech. All rights reserved. 
// 

#import "ViewController.h" 
#import "custom.h" 
@interface ViewController() 
{ 
    NSDictionary *dic_property; 

} 
@end 

@implementation ViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    [NSThread detachNewThreadSelector:@selector(fetchdata) toTarget:self withObject:nil]; 
    //[NSThread detachNewThreadSelector:@selector(arrycount) toTarget:self withObject:nil]; 

    self.arrayCounts = [NSMutableArray array]; 


    NSLog(@"array count=%d",self.arrayCounts.count); 
    [self.tableview reloadData]; 
    // Do any additional setup after loading the view, typically from a nib. 
} 
//-(void)arrycount 
//{ 
// for (int i = 0; i<[[dic_property objectForKey:@"Data"] count]; i++) { 
//  [self.arrayCounts insertObject:[NSString stringWithFormat:@"0"] atIndex:i]; 
// } 
// 
//} 
-(void)fetchdata 
{ 
    NSString *login= [[NSString stringWithFormat:@"http://men_dry.php"]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 

    NSLog(@"----%@", login); 
    NSURL *url = [NSURL URLWithString:[login stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 
    //-- Get request and response though URL 
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url]; 


    [NSURLConnection sendAsynchronousRequest:request 
             queue:[NSOperationQueue mainQueue] 
          completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { 
           dispatch_async(dispatch_get_main_queue(), ^{ 
            if (data) { 
             dic_property= [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; 
             NSLog(@"%@", dic_property); 
             NSLog(@"counts=%d",[[dic_property objectForKey:@"Data"]count]); 
             for (int i = 0; i<[[dic_property objectForKey:@"Data"] count]; i++) { 
                [self.arrayCounts insertObject:[NSString stringWithFormat:@"0"] atIndex:i]; 
               } 

             [self.tableview reloadData]; 
            } 
            else { 
             NSLog(@"network error, %@", [error localizedFailureReason]); 
            } 
           }); 

          }]; 


} 


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ 
    return self.arrayCounts.count; 
    // return [[dic_property objectForKey:@"Data"]count]; 
} 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    custom *cell; 
    static NSString *simpleTableIdentifier = @"customcell"; 

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

    if (cell == nil) 
     cell = [[[NSBundle mainBundle] loadNibNamed:@"customcell" owner:self options:nil] objectAtIndex:0]; 

    cell.lblcount.text = self.arrayCounts[indexPath.row]; 
    cell.lbltitle.text=[[[dic_property objectForKey:@"Data"]objectAtIndex:indexPath.row]objectForKey:@"Name"]; 
    cell.lblcount.tag=indexPath.row; 
    [cell.stepper addTarget:self action:@selector(itemsChange:) forControlEvents:UIControlEventValueChanged]; 
    return cell; 
} 
- (void)itemsChange:(UIStepper*)stepper 
{ 
    CGPoint cursorPosition = [stepper convertPoint:CGPointZero toView:self.tableview]; 
    NSIndexPath *indexPath = [self.tableview indexPathForRowAtPoint:cursorPosition]; 

    custom *currentCell = (custom *)[self.tableview cellForRowAtIndexPath:indexPath]; 


    currentCell.lblcount.text=[NSString stringWithFormat:@"%f",[stepper value]]; 

    [self.arrayCounts replaceObjectAtIndex:indexPath.row withObject:[NSString stringWithFormat:@"%f",[stepper value]]]; 
} 

- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

- (IBAction)placeorder:(id)sender { 
} 
@end 

Я застрял на три дня, пожалуйста, решить мою проблему Спасибо заранее.

+0

хотите использовать массив? – Vvk

+0

no Я не использую массив onle pass статическое значение в tableView numberOfRowsInSection.i использует пользовательскую ячейку в раскадровке. –

+0

, но Arpit вам нужно использовать массив insted из статического значения, поскольку ячейка reusable в tableview. – Vvk

ответ

0

@Arpit замените ваш код на Arry.

viewController.h


#import <UIKit/UIKit.h> 

@interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate> 

@property (weak, nonatomic) IBOutlet UITableView *tableview; 
@property (strong, nonatomic)NSMutableArray *arrayCounts; 
- (IBAction)placeorder:(id)sender; 

@property (weak, nonatomic) IBOutlet UIButton *placeorder; 

@end 

ViewController.m

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    [NSThread detachNewThreadSelector:@selector(fetchdata) toTarget:self withObject:nil]; 

    self.arrayCounts = [NSMutableArray array]; 
    NSLog(@"array count=%lu",(unsigned long)self.arrayCounts.count); 
} 

-(void)fetchdata 
{ 
    NSArray *tempArray = @[@{@"Dry_cleaning" : @"49", 
          @"Iron":@"5", 
          @"Name":@"Shirt/Tees", 
          @"Wash":@"20", 
          @"Wash_Iron":@"19", 
          @"id":@"1"}, 
          @{@"Dry_cleaning" : @"49", 
          @"Iron":@"5", 
          @"Name":@"Kurta(short)", 
          @"Wash":@"20", 
          @"Wash_Iron":@"19", 
          @"id":@"2"}, 
          @{@"Dry_cleaning" : @"49", 
          @"Iron":@"5", 
          @"Name":@"Kurta(Long)", 
          @"Wash":@"15", 
          @"Wash_Iron":@"20", 
          @"id":@"3"}, 
          @{@"Dry_cleaning" : @"50", 
          @"Iron":@"5", 
          @"Name":@"Shorts", 
          @"Wash":@"15", 
          @"Wash_Iron":@"19", 
          @"id":@"4"}, 
          @{@"Dry_cleaning" : @"51", 
          @"Iron":@"5", 
          @"Name":@"Trousers/Pyjamas", 
          @"Wash":@"20", 
          @"Wash_Iron":@"19", 
          @"id":@"5"}]; 


    // remove comment from below code and add where responce will come. ----------------- 

    // NSArray *tempArray = dic_property[@"Data"]; 
    [tempArray enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { 
     NSMutableDictionary *dictValues = [NSMutableDictionary dictionaryWithDictionary:obj]; 
     [dictValues setValue:@"0" forKey:@"counts"]; 

     [self.arrayCounts addObject:dictValues]; 
    }]; 

    [self.tableview reloadData]; 
    //-------------------------------- 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ 
    return self.arrayCounts.count; 
    // return [[dic_property objectForKey:@"Data"]count]; 
} 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    custom *cell; 
    static NSString *simpleTableIdentifier = @"customcell"; 

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

    if (cell == nil) 
     cell = [[[NSBundle mainBundle] loadNibNamed:@"custom" owner:self options:nil] objectAtIndex:0]; 


    cell.lblCount.text = self.arrayCounts[indexPath.row][@"counts"]; 
    cell.lbltitle.text=self.arrayCounts[indexPath.row][@"Name"];; 

    [cell.stepper addTarget:self action:@selector(itemsChange:) forControlEvents:UIControlEventValueChanged]; 
    return cell; 
} 
- (void)itemsChange:(UIStepper*)stepper 
{ 
    CGPoint cursorPosition = [stepper convertPoint:CGPointZero toView:self.tableview]; 
    NSIndexPath *indexPath = [self.tableview indexPathForRowAtPoint:cursorPosition]; 

    custom *currentCell = (custom *)[self.tableview cellForRowAtIndexPath:indexPath]; 

    double value = [stepper value]; 

    [currentCell.lblCount setText:[NSString stringWithFormat:@"%d", (int)value]]; 

    self.arrayCounts[indexPath.row][@"counts"] = [NSString stringWithFormat:@"%d",(int)value]; 
} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
} 


- (IBAction)placeorder:(id)sender { 
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"counts != %@",@"0"]; 
    NSArray *filteredArray = [self.arrayCounts filteredArrayUsingPredicate:predicate]; 
    NSLog(@"yoyr arry:%@",filteredArray); 
} 

enter image description here

+0

Применить ur код и сообщить об этом –

+0

@ArpitPatel также обновит ваш viewDidLoad. – Vvk

+0

Попробуйте ур код, но когда я прокрутку TableView, все таблицы исчезли –

-1

Вы выполните неправильный путь для этого. Просто используйте array, которые имеют начальное значение 0 по всему индексу и задают значение массива для метки в cellForRowAtIndexPath, чем обновление значения индекса массива при щелчке по событию stepper, чем перезагрузка table с обновленным array.