【问题标题】:Passing a JSON string from one view to another将 JSON 字符串从一个视图传递到另一个视图
【发布时间】:2014-01-11 17:12:05
【问题描述】:

我有一个表格视图,我在其中解析一些 JSON 数据并将其显示在自定义单元格中。在一个视图中,我正在解析来自 Facebook 的特定用户的帖子。

我正在表格视图中显示预览,但我想将数据传递到另一个视图。例如,我在表格视图中阅读了一篇文章的预览,但我想阅读整篇文章。

当我单击该帖子(单元格)时,我应该被定向到一个新的视图控制器,在该控制器中显示完整的帖子(在标签或文本视图中)。

我该怎么做?

这是我将数据解析到表格视图的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.


    strURLToLoad = [[NSMutableString alloc] init];

    [btnFaceBook setTitle:@"link.com/json.php?name=Name" forState:UIControlStateDisabled];
    [btnTwitter setTitle:@"link1.com/json.php?name=Name" forState:UIControlStateDisabled];
    [btnTwitter2 setTitle:@"link2.com/json.php?name=Name" forState:UIControlStateDisabled];

    [btnFaceBook setBackgroundImage:[UIImage imageNamed:@"tab_selected.png"] forState:UIControlStateNormal];
    [btnFaceBook setBackgroundImage:[UIImage imageNamed:@"tab_unselected.png"] forState:UIControlStateSelected];

    [btnTwitter setBackgroundImage:[UIImage imageNamed:@"tab_selected.png"] forState:UIControlStateNormal];
    [btnTwitter setBackgroundImage:[UIImage imageNamed:@"tab_unselected.png"] forState:UIControlStateSelected];

    [btnTwitter2 setBackgroundImage:[UIImage imageNamed:@"tab_selected.png"] forState:UIControlStateNormal];
    [btnTwitter2 setBackgroundImage:[UIImage imageNamed:@"tab_unselected.png"] forState:UIControlStateSelected];



    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"PostsObject" owner:self options:nil];
    PostsObject *cell = [nib objectAtIndex:0];
    fontForCellText = cell.title.font;
    cellTextWidth = cell.title.frame.size.width;
    cellHeightExceptText = cell.frame.size.height - cell.title.frame.size.height;

    [self.navigationController setNavigationBarHidden:YES];

    self.tableView.separatorColor = [UIColor clearColor];

    // Setting Up Activity Indicator View
    self.activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    self.activityIndicatorView.hidesWhenStopped = YES;
    self.activityIndicatorView.center = self.view.center;
    [self.view addSubview:self.activityIndicatorView];
    [self.activityIndicatorView startAnimating];
    self.tableView.separatorColor = [UIColor clearColor];

    // Initializing Data Source
    movies = [[NSMutableArray alloc] init];

    [self btnFromTabBarClicked:btnFaceBook];
}

- (void)loadJSONFromCurrentURL
{
    [self.activityIndicatorView startAnimating];

    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:strURLToLoad]];

    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        [movies setArray:JSON];
        [self.activityIndicatorView stopAnimating];
        [self.tableView reloadData];

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
    }];

    [operation start];
}

- (IBAction)btnFromTabBarClicked:(UIButton *)sender
{
    //Unselect all 3 buttons
    btnFaceBook.selected = btnTwitter.selected = btnTwitter2.selected = NO;

    //Select the button that was clicked
    sender.selected = YES;

    //Set the string of an NSMutableString property called strURLToLoad with the URL
    //The URL is pre stored in the text of the UIButton in the Disabled text.
    [strURLToLoad setString:[sender titleForState:UIControlStateDisabled]];

    //Load the URL
    [self loadJSONFromCurrentURL];
}

// Table View Data Source Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (movies && movies.count) {
        return movies.count;
    } else {
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *simpleTableIdentifier = @"PostsObject";

    PostsObject *cell = (PostsObject *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"PostsObject" owner:self options:nil];
        cell = [nib objectAtIndex:0];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

    }

    NSDictionary *movie = [self.movies objectAtIndex:indexPath.row];
    NSString *strText = [movie objectForKey:[self getTextKey]];

    CGRect rect = cell.title.frame;
    rect.size.height = [self getHeightForText:strText];
    cell.title.frame = rect;
    cell.title.text = strText;
    cell.arrow.center = CGPointMake(cell.arrow.frame.origin.x, rect.origin.y + rect.size.height/2);
    cell.published.text = [movie objectForKey:@"published"];
    cell.twitterName.text = [movie objectForKey:[self getTwitterName]];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *movie = [self.movies objectAtIndex:indexPath.row];
    NSString *strText = [movie objectForKey:[self getTextKey]];

    CGFloat cellHeight = cellHeightExceptText + [self getHeightForText:strText];

    return cellHeight;
}

- (NSString *)getTextKey
{
    return btnTwitter.selected?@"tweet":@"message";
}

- (NSString *)getTwitterName
{
    return btnTwitter2.selected?@"user":@"user";
}

- (CGFloat)getHeightForText:(NSString *)strText
{
    CGSize constraintSize = CGSizeMake(cellTextWidth, MAXFLOAT);
    CGSize labelSize = [strText sizeWithFont:fontForCellText constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
    NSLog(@"labelSize.height = %f",labelSize.height);
    return labelSize.height;
}

【问题讨论】:

    标签: ios json parsing uitableview


    【解决方案1】:

    有很多方法可以做到这一点。

    您可以实现 tableview:didSelectRowAtIndexPath: 并在其中分配下一个 VC 并将您的数据传递给它的属性,然后呈现该 VC。

    或者您可以实现从表格单元到新 VC 的转场,然后在 prepareForSegue: 中将数据传递给它的属性。

    无论哪种方式,所呈现的 VC 都可以通过 viewDidLoad 将数据加载到 tis 视图中。

    就传递 JSON 而言,它并不是特别理想。您可能会考虑创建自己的基于 Objective-c 的模型对象,然后将 JSON 数据解析为这些模型对象,并在您的应用程序中使用这些模型对象。

    【讨论】:

      【解决方案2】:

      您可以使用自己的 init 方法将所需的适当数据传递给下一个视图控制器。为了向您展示这一点,我创建了一个名为 NextViewController 的新视图控制器,并编写了自己的自定义 init 方法,该方法将字典作为参数。我将此函数添加到头文件中,以便您的原始视图控制器可以访问它,并将字典添加为属性,以便您可以在该文件中的各种函数中访问它(实例变量也可以),导入NextViewController 的 .h 文件放入我的原始表视图的文件中,并在 tableView 的 didSelectRowAtIndexPath 函数中根据数据源数组中的 indexPath 抓取所选对象,在您的情况下为电影,并创建了一个 NextViewController 实例,通过它的 init 函数传入该字典。以下是相关代码:

      NextViewController 的 .h 文件

      @interface NextViewController : UIViewController
      
      - (id)initWithDictionary:(NSDictionary *)dictionary;
      
      @property (nonatomic, retain) NSDictionary *myDictionary;
      
      @end
      

      NextViewController 的 .m 文件:

      @interface NextViewController ()
      
      @end
      
      @implementation NextViewController
      
      - (id)initWithDictionary:(NSDictionary *)dictionary {
          self = [super initWithNibName:nil bundle:nil];
      
          self.myDictionary = dictionary;
      
          return self;
      }
      
      @end
      

      原来的tableViewController里面:

      - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
          // first deselect the cell so it doesn't stay highlighted
          [tableView deselectRowAtIndexPath:indexPath animated:YES];
      
          // then grab the json you want to pass from your tableView's datasource
          NSDictionary *selectedMovie = self.movies[indexPath.row];
      
          // create the nextViewController and pass in the appropriate dictionary to it
          NextViewController *nextVC = [[NextViewController alloc] initWithDictionary:selectedMovie];
      
          // then tell our navigation controller to push this new controller onto the view stack
          [self.navigationController pushViewController:nextVC animated:YES];
      }
      

      如果这有帮助,或者您是否需要进一步说明,请告诉我。

      【讨论】:

      • 好的,看起来不错。但是如何从原始 tableViewController 中获取字符串以直接加载到 NextViewController 中的 UITextView? @迈克
      • 与在前一个视图控制器中的方式相同,您现在可以通过 self.myDictionary 属性将该字典用于 NextViewController 的文件的任何位置,因此您可以简单地从它并将其传递给 textView。 myTextView.text = myDictionary[@"correctKey"];
      • 嗯,我想不通。你能帮我一些代码吗? @迈克
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      相关资源
      最近更新 更多