在我的Storyboard中,我使用帶導航欄的UINavigationController來呈現視圖控制器。通過點擊我放置在導航欄中的UIBarButtonItem,該視圖控制器ViewController2被推送到堆棧。我在界面生成器中通過將鼠標從欄按鈕拖動到ViewController2場景併爲segue選擇「push」進行連接。要返回到第一個視圖控制器,我有一個IBAction
,它調用popViewControllerAnimated
方法。我使用委託方法將數據發送回第一個視圖控制器,但ViewController2中的字符串沒有被髮送回ViewController。UINavigationController中的UIViewController不調用委託方法
如何將使用委託方法將ViewController2中輸入的文本傳遞迴第一個ViewController?
ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
ViewController.m
#import "ViewController.h"
#import "ViewController2.h"
@interface ViewController() <UITableViewDelegate,UITableViewDataSource,Vc2Delegate>
@property (strong,nonatomic) NSArray *tableArray;
@property (weak,nonatomic) IBOutlet UITableView *listTableView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.listTableView setDelegate:self];
[self.listTableView setDataSource:self];
self.tableArray = @[@"item 1",@"item 2",@"item 3"];
ViewController2 *vc2 = [[ViewController2 alloc] init];
[vc2 setDelegate:self];
}
# pragma mark - TableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.tableArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ItemCell" forIndexPath:indexPath];
cell.textLabel.text = [self.tableArray objectAtIndex:indexPath.row];
return cell;
}
#pragma mark - Delegate Method
- (void)returnFromVc2:(NSString *)userString {
NSLog(@"delegate text is %@",userString);
}
@end
ViewController2.h
#import <UIKit/UIKit.h>
@protocol Vc2Delegate <NSObject>
- (void)returnFromVc2:(NSString *)userString;
@end
@interface ViewController2 : UIViewController
@property (weak,nonatomic) id <Vc2Delegate> delegate;
@end
ViewController2.m
#import "ViewController2.h"
@interface ViewController2()
@property (weak,nonatomic) IBOutlet UITextField *textField;
@end
@implementation ViewController2
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (IBAction)toPreviousVC:(id)sender {
NSLog(@"user text is: %@",self.textField.text);
[self.delegate returnFromVc2:self.textField.text];
[self.navigationController popViewControllerAnimated:YES];
}
@end
那麼,如何將委託設置爲我推送的正確實例呢? – wigging
在這個地方你推視圖控制器。 –
啊,所以請將代表設置爲'prepareForSegue'而不是'viewDidLoad'? – wigging