【发布时间】:2012-10-23 09:21:13
【问题描述】:
我有两个视图控制器:视图控制器和 viewcontroller2nd。我在其中一个中有 UILabel,并且希望在单击 viewcontroller2nd 中的按钮(名为 Go)时更改它。我正在使用委托和协议来做到这一点。
代码如下所示:
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 并确认它正在被调用。
-
嗯,这是因为您没有将委托传递给第二个控制器。此外,代表永远不会被保留,否则您会有保留周期 - 内存问题。您应该在第二个控制器中将其声明为分配。
标签: iphone ios delegates protocols