我有兩個視圖控制器:視圖控制器和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