我有一个FirstViewController
and a SecondViewController
。我创建了一个按钮FirstViewController
为了以模态方式执行segueSecondViewController
.
In SecondViewController
我有一个 tableView 显示 8 个项目的列表,当我从该列表中选择一个项目时,我dismissViewControllerAnimated:
,回到FirstViewController
.
我想做的是将一个字符串传递回FirstViewController
.
我使用这篇文章作为我的代码的参考:关闭模态视图控制器并传回数据 https://stackoverflow.com/q/6203799/2032708
这就是我所拥有的:
在 FirstViewController.h 中
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "SecondViewController.h"
@interface FirstViewController : UIViewController <SecondDelegate>
@end
在 FirstViewController.m 中
#import "FirstViewController.h"
@interface FirstViewController ()
@end
@implementation FirstViewController
...
- (void)secondViewControllerDismissed:(NSString *)stringForFirst
{
NSString *theString = stringForFirst;
NSLog(@"String received at FirstVC: %@",theString);
}
@end
在 SecondViewController.h 中
#import <UIKit/UIKit.h>
@protocol SecondDelegate <NSObject>
-(void) secondViewControllerDismissed:(NSString *)stringForFirst;
@end
@interface SecondViewController : UIViewController <UITableViewDataSource,UITableViewDelegate>
{
__weak id myDelegate;
}
@property (nonatomic, weak) id<SecondDelegate> myDelegate;
@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@end
在 SecondViewController.m 中
#import "SecondViewController.h"
@interface SecondViewController ()
@end
@implementation SecondViewController
@synthesize myDelegate;
@synthesize myTableView;
...
- (int)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 8;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [atributoTableView dequeueReusableCellWithIdentifier:@"MainCell"];
if(cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MainCell"];
}
cell.textLabel.text = //strings from an array here;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if([self.myDelegate respondsToSelector:@selector(secondViewControllerDismissed:)])
{
[self.myDelegate secondViewControllerDismissed:@"SOME STRING HERE"];
NSLog(@"string passed");
}
[self dismissViewControllerAnimated:YES completion:nil];
NSLog(@"SecondViewController dismissed");
}
@end
当我运行该应用程序时,我可以从FirstViewController
to SecondViewController
,当我从 tableView 中选择一行时,我返回到FirstViewController
正好。问题是字符串“SOME STRING HERE”没有传回。
我缺少什么?
顺便说一句,我不确定这是否相关:我正在使用 ARC 和故事板。