将按下的按钮传递给另一个 View JSON

Posted

技术标签:

【中文标题】将按下的按钮传递给另一个 View JSON【英文标题】:Passing which button that was pressed to another View JSON 【发布时间】:2014-02-14 11:20:10 【问题描述】:

我在一个视图中有一个 NSMutableArray,我将一些 JSON 数据解析为一个表视图。我在底部也有三个按钮:按钮 1、按钮 2、按钮 3。如果我选​​择按钮 2,JSON 数据字符串将更改为链接 2 等...

现在,当我单击一个单元格时,值(文本)传递到第二个视图控制器中的 UITextView。但我想要的是也传递按下的按钮,因此 UITextView 的字符串名称解析正确。因为现在,当我选择例如按钮 2 并单击一个单元格时,第二个视图控制器上的文本视图变为空白,因为我只将字符串名称设置为 @"message",并在选择按钮 2 时将文本的字符串名称设置为是@“推文”。

这是我的代码:

@interface DEMOSecondViewController () 

@end

@implementation DEMOSecondViewController
@synthesize tableView = _tableView, activityIndicatorView = _activityIndicatorView;
@synthesize fontForCellText;
@synthesize btnFaceBook, btnTwitter, btnTwitter2;
@synthesize strURLToLoad;
@synthesize movies;

- (IBAction)showButtonMenu 
    [self.frostedViewController presentMenuViewController];


- (void)refresh:(UIRefreshControl *)refreshControl 
    [refreshControl endRefreshing];


-(UIStatusBarStyle)preferredStatusBarStyle
    return UIStatusBarStyleLightContent;


- (void)viewDidLoad

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

    UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
    [refreshControl setTintColor:[UIColor greenColor]];
    [refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];
    [self.tableView addSubview:refreshControl];

    strURLToLoad = [[NSMutableString alloc] init];

    [btnFaceBook setTitle:@"link-1.com/json.php" forState:UIControlStateDisabled];
    [btnTwitter setTitle:@"link-2.com/json.php" forState:UIControlStateDisabled];
    [btnTwitter2 setTitle:@"link-3.com/json.php" 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:UIActivityIndicatorViewStyleWhiteLarge];

    self.activityIndicatorView.color = [UIColor greenColor];


    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];


//This is where I change the data source when selecting a button
- (IBAction)btnFromTabBarClicked:(UIButton *)sender

    btnFaceBook.selected = btnTwitter.selected = btnTwitter2.selected = NO;

    sender.selected = YES;

    [strURLToLoad setString:[sender titleForState:UIControlStateDisabled]];

    [self loadJSONFromCurrentURL];


// Table View Data Source Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 

    return movies.count;



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


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

    if(indexPath.row == 0) 
        static NSString *Identifier1 = @"TableHeaderView";


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

            cell.backgroundColor = [UIColor clearColor];
            return cell;
        

     else 
        static NSString *Identifier2 = @"PostsObject";

        PostsObject *cell = [tableView dequeueReusableCellWithIdentifier:Identifier2];
        if (cell == nil) 
            NSArray *nib= [[NSBundle mainBundle] loadNibNamed:@"PostsObject" owner:self options:nil];
            cell = (PostsObject *)[nib objectAtIndex:0];
            cell.backgroundColor = [UIColor clearColor];
        

        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:[self getPostedTime]];
        cell.twitterName.text = [movie objectForKey:[self getTwitterName]];

        return cell;

    
    return 0;


//Here I am passing the selected cell data to (PostsNextView). I want to pass the string values of button 1, button 2 and button 3. How?
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

    NSDictionary *movie = [self.movies objectAtIndex:indexPath.row];
    PostsNextView *newView = [[PostsNextView alloc] init];
    newView.theMovie = movie;
    [self.navigationController pushViewController:newView animated:YES];


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

    if(indexPath.row == 0) 
        return 224;

     else 
        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 *)getPostedTime

    return btnTwitter.selected?@"posted":@"published";


- (NSString *)getTwitterName

    return btnTwitter2.selected?@"user":@"celebname";


- (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;


@end

正如您在第一个视图中看到的那样,我正在解析 3 个不同的链接。如何在 PostsNextView 的 viewDidLoad 中设置 if 语句?比如,如果选择了 btnFacebook: textView.text = [theMovie objectForKey:@"message"];如果选择 btnTwitter: textView.text = [theMovie objectForKey:@"tweet"]; ?

非常感谢您的解决方案!

【问题讨论】:

Passing Data between View Controllers的可能重复 【参考方案1】:

修订后的答案(这将是高级别的):

为每个按钮添加标签值 当一个按钮被点击时,您可以通过 getTag(也可以通过 setTag 设置标签)调用获取它的标签 - 请查看 API 了解详情

当您在创建下一个视图控制器时以编程方式加载它

PostsNextView *newView = [[PostsNextView alloc] init];
newView.theMovie = movie;
// You could add a call here to set the value
[newView setTheVaue:valueIWantToSet]
您将在 newView 控制器中创建一个名为 TheValue 的属性

当您实际调用更改为新的视图控制器时

    [self.navigationController pushViewController:newView animated:YES];

您想要的数据值已经设置好了。

【讨论】:

嗯,我不明白。顺便说一句,我没有使用 Storyboard .. @Jeef 我想我也没有! :) 我会考虑在按钮上添加一个“标签”。这样,在您的 btnFromTabBarClicked 中,您可以检测标签并确定单击了哪个按钮... 如果我设置一个@property int buttonType;在 PostsNextView 中?那么,如何从第一个视图中传递 buttonType 呢? 如何在按钮上添加“标签”?

以上是关于将按下的按钮传递给另一个 View JSON的主要内容,如果未能解决你的问题,请参考以下文章

如何将按下按钮时的数据添加到 Vue 3 的根目录或组件?

Objective-C:需要帮助跟踪以前按下的按钮

如何将自定义 UIControl 中按下的 UIButton 传递给我的视图控制器?

UIPopover 和传递数据 - 越来越近

突出显示被按下的按钮并取消突出显示未按下的按钮 SWIFT

Phaser 3 切换场景重叠文本