UISplitViewController使用委托传递字符串

时间:2014-10-29 16:31:31

标签: ios objective-c protocols uisplitviewcontroller

我正在使用拆分视图控制器来安装iPad应用。我按下按钮时尝试从rootSending Controll向detailReceiving Controller发送标签更改。我已阅读有关协议的教程,并提出了以下代码。当我单击rootSending上的按钮时,detailReceiving上的标签没有任何反应。我是否必须使用splitViewContoller执行其他操作,以便标签更新?不应该在收到消息后接受更改标签吗?

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

1 个答案:

答案 0 :(得分:0)

首先,没有init就永远不会有分配!但在这种情况下,即使你确实使用了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;
    }