重读您的问题,您会问第一个视图控制器如何打开第二个视图控制器并设置文本框。如果这确实是您想要做的,那么这是一个简单得多的问题,根本不需要委托协议或委托。
前面的两个答案是通过代表们的讨论得出的,但其目的是解决不同的问题。仅当您需要第二个控制器将某些内容传递回第一个控制器时才需要委托。但是,如果您只想让第二个控制器从第一个控制器接收某些内容,则很简单:
// FirstViewController.h
#import <UIKit/UIKit.h>
@interface FirstViewController : UIViewController
@end
其实现如下:
// FirstViewController.m
#import "FirstViewController.h"
#import "SecondViewController.h"
@implementation FirstViewController
- (NSString *)generateRandomText
{
NSString *result;
int random_num;
random_num = (arc4random() % 5 - 1) + 1;
if (random_num == 1)
result = @"hello1";
else if (random_num == 2)
result = @"hello2";
else if (random_num == 3)
result = @"hello3";
else if (random_num == 4)
result = @"hello4";
return result;
}
// if you're using NIBs, it might be something like...
// you only need this method if you're using NIBs and you've manually hooked a button up to this
// if you're using segues, get rid of `goToNextViewController` and just use the following `prepareForSegue
- (IBAction)goToNextViewController:(id)sender
{
SecondViewController *secondController = [[SecondViewController alloc] initWithNibName:@"SecondView" bundle:nil];
secondController.textFromParent = [self generateRandomText];
[self.navigationController pushViewController:secondController animated:YES];
}
// if you're using segues, give your segue an identifier, e.g. toSecondViewSegue, in Interface Builder and reference the exact same identifier here
// if you're not using segues, you don't need this prepareForSegue method
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"toSecondViewSegue"])
{
SecondViewController *destinationController = segue.destinationViewController;
destinationController.textFromParent = [self generateRandomText];
}
}
@end
你的第二个控制器可能看起来像:
// SecondViewController.h
#import <UIKit/UIKit.h>
@interface SecondViewController : UIViewController
@property (strong, nonatomic) NSString *textFromParent;
@property (weak, nonatomic) IBOutlet UILabel *label;
@end
通过如下实现:
// SecondViewController.m
#import "SecondViewController.h"
@implementation SecondViewController
@synthesize textFromParent = _textFromParent;
@synthesize label = _label;
- (void)viewDidLoad
{
[super viewDidLoad];
self.label.text = self.textFromParent;
}
@end