如何在不使用prepareForSegue的情况下设置类的委托

时间:2014-02-13 11:57:43

标签: ios iphone delegation

我希望他们能够互相交流两节课。 A类包含tableView,当用户点击表行时,我会触发didSelectRowAtIndexPath方法。在这个方法中,我需要通过委托告知B类。我知道代理如何工作,但很难在不使用prepareForSegue方法的情况下设置如何设置A的委托。

通常我会在设置代理时执行此操作

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"goToManipulator"]) {
        ManipulatorViewController *secondVC = (ManipulatorViewController *) segue.destinationViewController;
        [secondVC setDelegate:self];
    }
}

但是如何在不使用prepareForSegue的情况下设置委托?

提前致谢

编辑:

这就是我的故事板结构的样子。 "接收器" viewcontroller是一个将获取数据并显示在"当前名称"标签取决于在"发件人"的表格视图中选择了什么? viewcontroller,最靠近右边。

http://oi62.tinypic.com/2li99w1.jpg

4 个答案:

答案 0 :(得分:1)

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ManipulatorViewController *secondVC = [[ManipulatorViewController alloc] init...];
    [secondVC setDelegate:self];

    //if you use push transition in UINavigationController
    [self.navigationController pushViewController:secondVC animated:YES];

    //if you use modal transition
    [self presentViewController:secondVC animated:YES completion:nil]
}

init...表示初始化取决于您的程序架构。

修改

如果您想从故事板中获取secondVC,请使用

UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
    ManipulatorViewController* secondVC = [storyboard instantiateViewControllerWithIdentifier:@"secondVC"];

不要忘记在storyboard中为viewController添加标识符。

答案 1 :(得分:0)

我理解你的用例如下:

在Receiver中,您打开发件人。在那里你选择一个值,并在选择了你想要告诉接收者的值的新值。

您可以在Sender上创建一个Receiver实现的协议。然后,在捕获Sender中所选值的函数中,调用协议方法(例如didSelectNewName()或其他东西)。

当然,您需要一个Receiver句柄,通常通过委托获得。但是,如果使用segue或其他方法从Receiver转换为Sender,您将同样有机会设置发件人的委托。

如果这不是您想要的,请详细说明您如何初始化发件人,以及为什么不希望segue。

答案 2 :(得分:0)

在点击A的单元格时,是否已实例化View Controller B?如果是,并且您没有使用prepareForSegue来获取其他View Controller的身份,那么使用NSNotification Center可能会更好。在View Controller A的didSelectRowAtIndex方法中,您可以输入

[[NSNotificationCenter defaultCenter] postNotificationName:@"yourNotificationName" object:nil userInfo:dictionaryWithYourData];

它会向您的整个应用程序发出通知,表明该行已被选中。如果您预先使用您想要的任何信息初始化字典,则可以通过userInfo传递。然后,在View Controller B的viewDidLoad中,添加

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(yourMethod:) name:@"yourNotificationName" object:nil];

让它听取通知。您设置的选择器将接受NSNotification作为参数,因此您可以按如下方式获取字典:

- (void)yourMethod:(NSNotification *)notification
{
    NSDictionary *yourData = [notification userInfo];
}

答案 3 :(得分:0)

这就是我的所作所为。

在.m文件中:

@implementation ViewController{

   SecondViewController *svc;

}

然后在下面你需要这样的动作:

- (IBAction)goToView2:(id)sender {
    if (!svc) {
        svc = [[self storyboard] instantiateViewControllerWithIdentifier:@"View2"];
        [svc setDelegate:self];
    }
    [[self navigationController] pushViewController:svc animated:YES];
}

只需确保将StoryBoard中的正确标识符设置为声明协议的ViewController。