如何在故事板中的两个视图控制器之间传递数据?

时间:2013-11-11 12:19:35

标签: ios storyboard initialization

假设我们有2个名为 ViewControllerA 的视图控制器   和 ViewControllerB

当我没有使用故事板时,我有以下初始化机制。

// ViewControllerA.h

@interface ViewControllerA : UIViewController

@end

// ViewControllerA.m

@implementation ViewControllerA

- (IBAction)showViewControllerB:(id)sender {
    ViewControllerB *vcB = [[ViewControllerB alloc] initWithTitle:@"Test"];
    [self.navigationController pushViewController:vcB animated:YES];
 }

@end

// ViewControllerB.h

@interface ViewControllerB : UIViewController

- (id)initWithTitle:(NSString *)title;

 @end

// ViewControllerB.m

@interface ViewControllerB()

@property (nonatomic, retain) NSString *title;//Private scope.

@end

@implementation ViewControllerB

- (id)initWithTitle:(NSString *)title {
    self = [self init];
    if(self)
    {
        _title = title;
    }
    return self; 
}

@end

如何在不在公共范围内声明title属性(ViewControllerB.h)的情况下使用故事板实现此目的?

提前致谢。

3 个答案:

答案 0 :(得分:2)

您可以使用KVC访问该媒体资源。

- (IBAction)showViewControllerB:(id)sender 
{
    ViewControllerB *viewcontroller = [self.storyboard instantiateViewControllerWithIdentifier:@"ViewControllerB"]; // corresponding to the storyboard identifier
    [viewcontroller setValue:@"Hello World" forKey:@"title"];
    [self.navigationController pushViewController:viewcontroller animated:YES];
}

答案 1 :(得分:0)

UIStoryboard *storyboard=self.storyboard;

ViewControllerB *vc=(ViewControllerB*)[storyboard instantiateViewControllerWithIdentifier:@"Scene_Id"];

[vc setTitle:@"your Text"];

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

答案 2 :(得分:0)

如果您确实需要将该属性设为私有,则可以使用objc_setAssociatedObject将数据附加到vcB对象。或者您可以将属性保存在AppDelegate中,并在ViewControllerB初始化时从那里获取它。