我有FirstViewController
和SecondViewController
。我在FirstViewController
中創建了一個按鈕,以便以模態方式執行到SecondViewController
。將數據傳遞給dismissViewControllerAnimated
在SecondViewController
我有一個tableView顯示了8個項目的列表,我從列表中選擇一個項目,我dismissViewControllerAnimated:
,返回FirstViewController
。
我想要做的是將字符串傳遞迴FirstViewController
。
我用這篇文章作爲我的代碼的參考:dismissModalViewController AND pass data back
所以這是我:
在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
in 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
到SecondViewController
,當我從的tableView選擇一行我回去FirstViewController
就好了。問題在於字符串「某些字符串在這裏」沒有被傳回。
我錯過了什麼?順便說一句,我不確定這是否相關:我正在使用ARC和Storyboards。
你在設置代表嗎?它是否到了'[self.myDelegate secondViewControllerDismissed ...'? – iDev 2013-03-08 19:59:30
非常好格式化的問題:) – Sid 2013-03-08 22:41:07