UINavigationControllers: How to pass value to higher (parent?) controller in stack?

。_饼干妹妹 提交于 2020-01-06 05:30:09

问题


I have SendingController which push to nav stack SendingDeatilsController (which one has a TableView). User should should pick in TableView one row (it checked by Checkmark) and I would like to pass the value of this row (let it will NSString object) to the SendingController.

How can I realize this behaviour in my application? And is SendingController parent for SendingDetailController (attribute parentController of SDC refers to SC) ??


回答1:


If you want to implement this behaviour, pass the SendingDetailController a reference to the previous view controller. This way the detail view controller can send a message to the previous one on the stack.

In your SendingDetailController define a weak reference :

// in .h
SendingController *sendingController;
@property(assign) SendingController *sendingController;

// in .m
@synthesize sendingController;

-(void)tableView:(UITableView *)tableView
 didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // retrieve the string and send the message
    [sendingController didSelectString:theString];
}

Now before pushing the SendingDetailController on the stack don't forget to set its sendingController property.

// .m
// where you push the vc
if(!sendingDetailController) {
    sendingDetailController = [[SendingDetailController alloc]
                               initWithNibName:@"TheNIBName"
                                        bundle:nil];
    sendingDetailController.sendingController = self;
}
[self.navigationController pushViewController:sendingDetailController
                                     animated:YES];

and write the method that will recieve the string.

-(void)didSelectString:(NSString *)aString {
    // do anything with string
    [self.navigationController popViewControllerAnimated:YES];
}

This should do the job.




回答2:


For easy asynchronous communication between different UIViewControllers, you may want to look at NSNotification and NSNotificationCenter.

There are plenty tutorials on the web and some good answers here at SO that can show you how to do that exactly.



来源:https://stackoverflow.com/questions/6800226/uinavigationcontrollers-how-to-pass-value-to-higher-parent-controller-in-sta

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!