iphone - 如何访问 UINavigationController 中以前的 View 元素

标签 iphone objective-c ios xcode

我有一个 UINavigationController,我在其中加载不同的 View Controller 。我想知道如何访问上一个 View 的元素(如标签等)。 这是一个例子。

查看A myLabel.text = @"第一次查看";

(用户移至 View B)

View B (用户输入了一条消息,我需要在 View A 中显示该消息) 像 ViewA.myLabel.text = @"用户输入的消息"

我尝试了很多东西,但没有找到任何有用的东西。请帮忙..

我使用的是 Xcode 4,没有 ARC,也没有 Storyboard 。

谢谢 山姆


编辑:

我想更新 View A 的 viewController 中声明的属性,而不是直接更新标签。我的标签使用该属性进行更新。就像推送 viewController 时一样,我们可以传递如下值。

ViewA *myView = [[ViewA alloc] init];
myView.title = @"View B" ;
myView.tableView.tag = 3;
myView.myTextView.text = @"Some Text";
[self.navigationController pushViewController:myView animated:YES];
[myView release];

有没有办法在弹出 ViewB 并返回 ViewA 时将这些值传递给 ViewA 的 ViewController 属性?

实际场景如下:用户可以选择在textView中写入消息,或者可以使用预定义的模板。如果他单击模板按钮,他将进入预定义模板列表,他可以在其中选择任何预定义消息。现在我希望当用户单击任何预定义消息时,包含预定义消息列表的 View 会弹出,并且他选择的消息会自动填充在主视图的 textView 中。实现这一目标的最佳方法是什么?

TIA 山姆

最佳答案

您应该将 AViewController 设置为 BViewController 的委托(delegate),以便您可以在特定事件后向其返回消息。使用委托(delegate)还可以更好地解耦 ViewController。

在您的 BViewController 中,定义如下协议(protocol):

BViewController.h:

@protocol BViewControllerDelegate <NSObject>
- (void)viewB:(UIViewController *)didEnterMessage:(NSString *)message;
@end

并添加委托(delegate)属性:

@property (nonatomic, weak) id <BViewControllerDelegate> delegate;

当用户在 BViewController 中输入消息并点击弹出 BViewController 以向 AViewController 显示的按钮时,执行以下操作:

- (IBAction)messageEntered {
  if ([self.delegate respondsToSelector:@selector(viewB:didEnterMessage:)]) {
    [self.delegate viewB:self didEnterMessage:self.yourTextField.text];
  }
}

你的AViewController应该实现BViewControllerDelegate协议(protocol),如下所示:

AViewController.h:

@interface AViewController <BViewControllerDelegate>

当你的 AViewController 创建 BViewController 时,它应该在呈现它之前将自己设置为它的委托(delegate)。可能看起来像这样:

BViewController *bvc = [[BViewController alloc] init…];
bvc.delegate = self;

最后,你的 AViewController 应该实现 viewB:didEnterMessage: 方法:

- (void)viewB:(UIViewController *)didEnterMessage:(NSString *)message {
  self.myLabel.text = message;
}

恕我直言,这是最干净的方法。

关于iphone - 如何访问 UINavigationController 中以前的 View 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9274376/

相关文章:

iphone - Twitter+oAuth 引擎在尝试发布状态时返回 401

iphone - ScrollView 中的砌体布局

ios - UIActivityIndi​​catorView 未呈现

ios - RestKit - 到同一实体的关系映射创建无限循环

iOS 7 : Custom UITableViewCell content doesn't move expected on editing?

ios - 如何使 UITextView 在 Swift 中可选择

ios - 使用 AVCaptureMetadataOutput 和 AVFoundation 扫描条形码

iphone - 如何使用 Xcode 调试生产推送通知?

iphone - 如何从 iPhone 应用程序中启动 iPhone 日历?

ios - 检查 iOS 是否通过应用程序显示系统警报的可靠方法? (如定位服务等)