我正在使用委托尝试从viewcontroller中的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;
}
我的问题是,即使我从第一个视图控制器调用它,上面的方法也不会被调用。
这有点混乱,很遗憾地说.....您在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;
您可以直接调用此方法无需创建委托。
ViewController2 *obj=[[ViewController2 alloc] init];
[obj updateLabelWithString:@"title"];
[self.navigationController pushViewController:obj animated:YES];