0

在我的 Storyboard 中,我使用带有导航栏的 UINavigationController 来呈现视图控制器。这个视图控制器 ViewController2 通过点击我放置在导航栏中的 UIBarButtonItem 被推送到堆栈。我在 Interface Builder 中通过从栏按钮拖动到 ViewController2 场景并为 segue 选择“push”来建立这种连接。要返回第一个视图控制器,我有一个IBAction调用该方法的popViewControllerAnimated方法。我正在使用委托方法将数据发送回第一个视图控制器,但来自 ViewController2 的字符串没有被发送回 ViewController。

如何使用委托方法将 ViewController2 中输入的文本传递回第一个 ViewController?

视图控制器.h

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end

视图控制器.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

视图控制器2.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
4

1 回答 1

0

您将委托设置为一个局部变量,该变量与您推送的实例不同。

- (void)viewDidLoad {
    ....
    ViewController2 *vc2 = [[ViewController2 alloc] init];
    [vc2 setDelegate:self];
    ....
}

您还应该养成检查您的代表是否可以响应发送的消息的习惯。

- (IBAction)toPreviousVC:(id)sender {
    NSLog(@"user text is: %@",self.textField.text);

    if ( [self.delegate respondsToSelector(@selector(returnFromVc2:))] ) {
        [self.delegate returnFromVc2:self.textField.text];
    }
    [self.navigationController popViewControllerAnimated:YES];
}
于 2013-10-13T16:37:39.867 回答