我有两个视图控制器:视图控制器和viewcontroller2nd。我在其中的一个UILabel中,并且想要在viewcontroller2nd中的按钮(名为Go)被点击时更改它。我正在使用代表和协议来完成它。在两个视图控制器之间使用代理iphone
的代码看起来是这样的:
ViewController.h
#import <UIKit/UIKit.h>
#import "ViewController2nd.h"
@interface ViewController : UIViewController <SecondViewControllerDelegate>
{
IBOutlet UILabel *lbl;
ViewController2nd *secondview;
}
-(IBAction)passdata:(id)sender;
@end
ViewController.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。代码有什么问题?需要一些指导。
您是否检查了第一个视图控制器的changeLabel被调用?尝试把NSLog,并确认它正在调用。 – applefreak
它没有被调用... – lakesh
嗯,这是因为你没有通过委托给第二个控制器。此外,代表永远不会被保留,否则你有保留周期内存的问题。您应该将其声明为在第二个控制器中分配。 – applefreak