我有两个视图控制器:视图控制器和 viewcontroller2nd。我在其中一个中有 UILabel,并且希望在单击 viewcontroller2nd 中的按钮(名为 Go)时更改它。我正在使用代表和协议来做到这一点。
代码如下所示:
视图控制器.h
#import <UIKit/UIKit.h>
#import "ViewController2nd.h"
@interface ViewController : UIViewController <SecondViewControllerDelegate>
{
IBOutlet UILabel *lbl;
ViewController2nd *secondview;
}
-(IBAction)passdata:(id)sender;
@end
视图控制器.m
#import "ViewController.h"
#import "ViewController2nd.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void) changeLabel:(NSString*)str{
lbl.text = str;
}
-(IBAction)passdata:(id)sender{
ViewController2nd *second = [[ViewController2nd alloc] initWithNibName:nil bundle:nil];
[self presentViewController:second animated:YES completion:NULL];
}
@end
Viewcontroller2nd.h
#import <UIKit/UIKit.h>
@protocol SecondViewControllerDelegate <NSObject>
@optional
-(void) changeLabel:(NSString*)str;
@end
@interface ViewController2nd : UIViewController{
IBOutlet UIButton *bttn;
id <SecondViewControllerDelegate> delegate;
}
@property (retain) id delegate;
-(IBAction)bttnclicked;
-(IBAction)back:(id)sender;
@end
ViewController2nd.m
#import "ViewController2nd.h"
#import "ViewController.h"
@interface ViewController2nd ()
@end
@implementation ViewController2nd
@synthesize delegate;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)bttnclicked{
[[self delegate] changeLabel:@"Hello"];
}
-(IBAction)back:(id)sender{
[self dismissViewControllerAnimated:YES completion:NULL];
}
@end
两个视图之间的控件传递工作正常。但是,当我单击 viewcontroller2nd 中的 go 按钮时,它不会将标签的值更改为 Hello。代码有什么问题?需要一些指导。