2014-10-29 52 views
0

我正在爲iPad應用程序使用分割視圖控制器。我試圖在按下按鈕時從rootSending Controll向detailReceiving Controller發送標籤更改。我已閱讀了有關協議的教程,並提供了下面的代碼。當我點擊rootSending上的按鈕時,detailReceiving上的標籤沒有任何反應。我是否必須使用splitViewContoller做其他事情,以便標籤更新?接收消息時,不應該細節接收更改標籤嗎?使用委託來傳遞字符串的UISplitViewController

rootSending.h

#import <UIKit/UIKit.h> 
@protocol TestDelegate <NSObject> 
-(void)tester:(NSString*)testString; 
@end 

@interface rootSending : UIViewController 
@property (nonatomic, assign) id <TestDelegate> delegate; 
@end 

rootSending.m

#import "rootSending.h" 

@implementation rootSending 
@synthesize delegate; 
-(void)viewDidLoad{ 

} 
-(IBAction)buttonPressed:(id)sender{ 

[delegate tester:@"button pressed"]; 
} 

@end 

detailReceiving.m

#import "detailReceiving.h" 
#import "rootSending.h" 
@interface detailReceiving()<TestDelegate>{ 
IBOutlet UILabel *label2; 
} 
@end 
@implementation detailReceiving 
-(void)viewDidLoad{ 
rootSending *obj = [rootSending alloc]; 
obj.delegate = self ; 
} 
-(void)tester:(NSString *)testString{ 
label2.text = testString; 
} 

@end 

回答

0

首先,永遠不會有一個頁頭沒有初始化!但是在這種情況下,即使你使用了alloc/init,它仍然不起作用,因爲它只是創建一個新的rootSending實例,而不是你在分割視圖中創建的實例。你需要去一個你有,你可以從拆分視圖控制器獲得參考,

-(void)viewDidLoad{ 
rootSending *obj = (rootSending *)self.splitViewController.viewControllers.firstObject; 
obj.delegate = self; 
} 

編輯後:

如果你的伴侶控制器嵌入導航控制器,那麼你需要讓導航控制器的topViewController獲取您的參考。

-(void)viewDidLoad{ 
    UINavigationController *nav = (UINavigationController *)self.splitViewController.viewControllers.firstObject; 
    xmlListOfItems *obj = (xmlListOfItems *)nav.topViewController; 
    obj.delegate = self; 
    } 
+0

偉大的工程!好的提示在alloc上。我只知道我不想啓動它。 – iDev 2014-10-29 17:32:57

+0

如果故事板是分屏視圖 - >導航控制器 - >視圖,該怎麼辦?這不起作用:xmlListofItems * obj =(xmlListofItems *)self.splitViewController.navigationController.viewControllers.firstObject; – iDev 2014-10-29 18:02:56

+0

@iDEV,你真的需要考慮你的控制器結構,以及你的控制器如何相互關聯 - 這是你必須學習的非常重要的iOS編程基礎知識。我已經更新了我的答案,告訴你如何做到這一點,但你需要做一些學習來學習這些東西。 – rdelmar 2014-10-29 18:42:04