objective-c - 在另一个 View Controller 中更改标签的文本

标签 objective-c uiviewcontroller uilabel

我有一个名为 FirstViewController 的 View Controller ,还有一个名为 SecondViewController 的 View Controller 。我用

呈现第二个 View Controller
 UIViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:@"mainController"];
[self presentViewController:controller animated:YES completion:nil];

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

最佳答案

你可以使用委托(delegate)模式

首先创建你的委托(delegate)协议(protocol)

@class SecondViewController;

@protocol SecondViewControllerDelegate

-(void) updateLabelWithString:(NSString*)string

@end

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

在你的 IBAction 中连接到你的 UIButton

[self.delegate updateLabelWithString:yourString];

在 FirstViewController.h 中

#import "SecondViewController.h"

@interface FirstViewController : UIViewController <SecondViewControllerDelegate>

在 FirstViewController.m 中

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

然后在创建 Controller 实例时,将 FirstViewController 设置为 mainViewController 的委托(delegate)

controller.delegate = self;

关于objective-c - 在另一个 View Controller 中更改标签的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18193973/

相关文章:

ios - 创建IOS 3D效果

ios - TableView :numberOfRowsInSection error when searching

ios - 如何避免在 TableView 列表中使用一百万个 View Controller ?

ios - UILabel:背景相关颜色

ios - UILabel 子类 - 尽管标签高度正确,但文本在底部被截断

iphone - 如何在UILabel文本中显示版权图标?

objective-c - 在 ViewController 之间传递 NSArray。是通过指针还是通过复制?

ios - 由于 MPMoviePlayerViewController,应用程序在 ios 中崩溃

swift - 如何从 AppDelegate 中的supportedInterfaceOrientationsFor 方法获取调用ViewController?

html - iOS - UIWebView 不显示 HTML