在另一个视图控制器中更改标签的文本

use*_*438 3 objective-c uiviewcontroller uilabel

我有一个名为FirstViewController的视图控制器,第二个名为SecondViewController.我提出了第二个视图控制器

 UIViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:@"mainController"];
[self presentViewController:controller animated:YES completion:nil];
Run Code Online (Sandbox Code Playgroud)

在SecondViewController的.m中,我想在FirstViewController中更改UILabel的文本.但是,标签的文本未更新.如何在SecondViewController中按下UIButton时更新FirstViewController的标签?

Chr*_*ult 6

您可以使用委托模式

首先创建您的委托协议

@class SecondViewController;

@protocol SecondViewControllerDelegate

-(void) updateLabelWithString:(NSString*)string

@end

@property (weak, nonatomic) id<SecondViewControllerDelegate>delegate;
Run Code Online (Sandbox Code Playgroud)

在你的IBAction连接中UIButton

[self.delegate updateLabelWithString:yourString];
Run Code Online (Sandbox Code Playgroud)

在FirstViewController.h中

#import "SecondViewController.h"

@interface FirstViewController : UIViewController <SecondViewControllerDelegate>
Run Code Online (Sandbox Code Playgroud)

在FirstViewController.m中

-(void) updateLabelWithString:(NSString*)string {
   label.text = string;
} 
Run Code Online (Sandbox Code Playgroud)

然后在创建控制器实例时,将FirstViewController设置为mainViewController的委托

controller.delegate = self;
Run Code Online (Sandbox Code Playgroud)