0

我在parentViewController一個parentViewControllersubView,在viewWillAppear我加入了subviewself.view和我設置子視圖的delegateself。當我試圖在子視圖中使用push另一個視圖控制器的委託時,它不起作用,我檢查了委託的值並得到了「null」。ParentViewController和子視圖:設置委託返回null

我的主要想法:當用戶點擊子視圖中的按鈕,我需要推動另一個viewController使用parentViewController的navigationController

這裏是我的代碼

//parentViewController.h 

#import "mysubView.h" 

@interface parentViewController : UIViewController <mysubViewDelegate> 
. 
.//Some properties here 
. 
@end 

在實現文件:

//parentViewController.m 

-(void) viewWillAppear:(BOOL)animated 
{ 
    [super viewWillAppear:animated]; 

    mysubView *myView; 

    //GlobalObjects is to load the file in a certain language 
    myView = [[GlobalObjects loadNibNamed:@"mysubView" owner:self options:nil] objectAtIndex:0]; 

    //Print myView.delegate gets the correct value here 
    myView.delegate = self; 

    [self.view addSubview:myView]; 

} 
. 
. 
. 
-(void)pushViewControllerUsingDelegate:(UIViewController *)viewController 
{ 
    [self.navigationController pushViewController:viewController animated:YES]; 
} 

在mysubView.h:

//mysubView.h 

@protocol mysubViewDelegate <NSObject> 

-(void)pushViewControllerUsingDelegate:(UIViewController *)viewController; 

@end 

@interface mysubView : UIView< UITableViewDataSource, UITableViewDelegate> 
{ 
} 

@property (nonatomic , retain) id <mysubViewDelegate> delegate; 

-(IBAction)ButtonClicked:(UIButton *)sender; 


@end 

在mysubView.m

@implementation mysubView 
@synthesize delegate; 
. 
. 
. 

-(IBAction)ButtonClicked:(UIButton *)sender 
{ 
    newViewController *newController = [[newViewController alloc] initWithNibName:@"newViewController" bundle:nil]; 

    //Here is my problem in this line .. self.delegate is null here 
    [self.delegate pushViewControllerUsingDelegate:newViewController]; 
} 

-(void)pushViewControllerUsingDelegate:(UIViewController *)viewController 
{ 
    [self.delegate pushViewControllerUsingDelegate:viewController]; 
} 
@end 
+2

以大寫字母開始類,所以'ParentViewController','newViewController',... –

+0

您創建了多少個'mysubView'實例? – Wain

+0

我的課已經開始大寫字母,我很抱歉,但是當我寫這個問題時,我用了小寫字母 – Sawsan

回答

0
myView = [[GlobalObjects loadNibNamed:@"mysubView" owner:self options:nil] objectAtIndex:0]; 

使用mysubView而不是像如下GlobalObjects

myView = [[mysubView loadNibNamed:@"mysubView" owner:self options:nil] objectAtIndex:0]; 

請使用大寫字母,當您創建新class.this只是慣例,但你應該遵循它。

+0

那如何遠程回答這個問題?! – Petar