将参数从视图传递回另一个视图的UITableView的单元格

aec*_*tci 1 iphone uitableview uinavigationcontroller

我有两个观点.第一个:FirstViewController第二个:SecondViewController

FirstViewController是我的UINavigationController的根控制器,在FirstViewController里面我有UITableView.在UITableView中单击单元格时,视图将导航到SecondViewController.在SecondViewController里面我有UILabel.我想将此UILabel的值分配给在导航栏中单击"返回"按钮时在FirstViewController中单击的单元格.我应该怎么做才能实现这个目标?

我可以通过创建:从FirstViewController传递值到SecondViewController:

SecondViewController*sv; sv.somestring = someanotherstring;

但无法在SecondViewController中实现此功能,以将值传递给FirstViewController中的NSString.

你可以帮我吗?

谢谢.AE

aro*_*oth 7

在iPhone SDK中处理此问题的典型方法是定义委托协议.例如:

@protocol SecondViewControllerDelegate
- (void) viewControllerWillDisappearWithLabelText: (NSString*)text;
@end
Run Code Online (Sandbox Code Playgroud)

然后你会添加一个delegate属性SecondViewController,如:

//in the .h file
@interface SecondViewController : UIViewController {
    //declare instance variables
}
@property(nonatomic, assign) id<SecondViewControllerDelegate> delegate;
@end

//in the .m file
@implementation SecondViewController

@synthesize delegate;

//[code...]
@end
Run Code Online (Sandbox Code Playgroud)

然后,您将更新FirstViewController以实现委托协议:

//in the .h file
@interface FirstViewController : UIViewController<SecondViewControllerDelegate> {
    //[instance variables]
}
//[methods and properties]
@end

//in the .m file
@implementation FirstViewController
//[code...]

- (void) viewControllerWillDisappearWithLabelText: (NSString*)text {
    //do whatever you need to do with the text
}

//[code...]
@end
Run Code Online (Sandbox Code Playgroud)

...并在FirstViewController创建时设置委托字段SecondViewController:

SecondViewController* sv = [[SecondViewController alloc] init]; 
sv.somestring = someanotherstring;
sv.delegate = self;
Run Code Online (Sandbox Code Playgroud)

最后,在SecondViewController你的实现viewWillDisappear大致如下:

- (void) viewWillDisappear: (bool)animated {
    [super viewWillDisappear:animated];
    if (self.delegate) {
        [self.delegate viewControllerWillDisappearWithLabelText: myLabel.text];
    }
}
Run Code Online (Sandbox Code Playgroud)