从另一个View Controller更改UILabel上的文本

时间:2017-06-26 19:04:55

标签: ios objective-c xcode

我使用委托来尝试从ViewController2中的UILabel更改文本。

在ViewController1.h中我有:

@protocol WelcomeDelegate

-(void) updateLabelWithString:(NSString*)string;

@end


@interface ViewController1 : UIViewController

@property (weak, nonatomic) id<WelcomeDelegate>delegate;

ViewController1.m内部:

- (void)presentWelcomeAlert {

UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
ViewController2* contentVC = [storyboard instantiateViewControllerWithIdentifier:@"ViewController2ID"];

[self.delegate updateLabelWithString:[NSString stringWithFormat:@"Welcome to the 11Health Family %@! We are here to accompany and support you through the journey as an ostomate. Our new Hydration Tracker is ready to follow your hydration levels. Tap 'Continue' to begin!", [dcsContext sharedContext].activeParticipant.firstName]];

UIViewController *rootVC = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
[rootVC presentViewController:contentVC animated:YES completion:nil];
}

在ViewController2.h中,我有:

#import "SignInViewController.h"


@interface WelcomePopoverViewController () <UIViewControllerTransitioningDelegate>
{
    SignInViewController *signInViewController;
}

在viewDidLoad中:

viewController1 = [[ViewController1 alloc] init];
[viewController1 setDelegate:self];

我在ViewController2.m中的方法:

- (void)updateLabelWithString:(NSString *)string {
welcomeLabel.text = string;
}

我的问题是,即使我从第一个视图控制器调用它,上面的方法也不会被调用。

2 个答案:

答案 0 :(得分:0)

这有点乱,抱歉说.....你在ViewController2中重新实例化ViewController1 .... 如果您只需要设置一次该标签,那么就抛弃所有委托/协议的东西,直接调用该方法:

- (void)presentWelcomeAlert {
   UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
   ViewController2* contentVC = [storyboard instantiateViewControllerWithIdentifier:@"ViewController2ID"];

   UIViewController *rootVC = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
   [rootVC presentViewController:contentVC animated:YES completion:^ {
   [contentVC updateLabelWithString:[NSString stringWithFormat:@"Welcome to the 11Health Family %@! We are here to accompany and support you through the journey as an ostomate. Our new Hydration Tracker is ready to follow your hydration levels. Tap 'Continue' to begin!", [dcsContext sharedContext].activeParticipant.firstName]];
   }];
}

然后在ViewController2.h中公开该方法:

-(void) updateLabelWithString:(NSString*)string;

答案 1 :(得分:0)

您可以直接调用此方法,无需创建委托。

ViewController2 *obj=[[ViewController2 alloc] init];
[obj updateLabelWithString:@"title"];
[self.navigationController pushViewController:obj animated:YES];