从第二个视图控制器返回到第一个视图控制器

3

我有两个视图控制器,第一个是带有TableView的视图控制器,第二个是带有标签按钮的视图控制器。当我在第二个视图控制器中点击按钮时,我需要返回到TableView并设置

cell.detailTextLabel.text

按钮上的标签文本。

我使用以下代码返回到第一个视图:

[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];

但是我如何从第二个视图设置标签到:
cell.detailTextLabel.text

in first view?????


你不能这样做。应该在viewWillAppear方法中完成。 - Martol1ni
即使在viewWillAppear中,如果不实现协议,也无法完成此操作。 - John Smith
@TeodorCarstea 虽然大体上是正确的,但关键的信息是,当一个活动的视图控制器想要触发在已接收 viewDidDisappear 的视图中更改某些内容时,无论你使用什么机制进行更新,都不应直接更新非活动视图(在 didReceiveMemoryWarning 的情况下,该视图可能已被释放)。你必须更新你的模型,并且只有当另一个视图控制器变为活动状态并接收到 viewWillAppear 时,才应执行 UI 更改。 - Rob
@RobertRyan,同意。问题是:你说“…不应直接更新非活动视图…”,这有什么用?即使你尝试这样做,更新非活动视图也不会产生任何可见的更改。因此,先是模型,然后是viewWillAppear,如你所说。 - John Smith
@TeodorCarstea 常见情况是在关闭子项之前如何更新父项。我实际上看到了另一个SO,正好讨论了这个主题,其中有人回答了一个非常详细的答案,说明如何使用委托来完成此操作,但在子项被关闭之前,委托的回调方法无意中更新了父视图,使用 self.label.text=...。所以,虽然Martol1ni的答案非常建设性,但没有冒犯他,有一个未被充分重视的事实,那就是不应该让委托方法更新UI。听起来我们是同意的。 - Rob
3个回答

2

我会在第二个视图控制器中定义一个协议和代理。

@protocol SecondViewController;

@interface SecondViewController : UIViewController

@property (nonatomic, assign) id<SecondViewController> delegate;

@end


@protocol SecondViewController <NSObject>
- (void)secondViewController:(SecondViewController *)controller didTappedOnButton:(UIButton *)button;
@end   

当按钮被点击时调用委托:

- (IBAction)buttonTapped:(UIButton *)sender
{
    // do somthing..

    // then tell the delegate about the button tapped
    [self.delegate secondViewController:self didTappedOnButton:sender];
}  

在你的第一个视图控制器中实现该协议。
@interface FirstViewController : UIViewController <SecondViewControllerDelegate>

当您推送第二个视图控制器时,将第一个视图控制器设置为第二个委托:
- (void)someMethodThatPushTheSecondViewController
{
    SecondViewController *svc = [[SecondViewController alloc] init];
    [self.navigationController pushViewController:svc animated:YES];
    svc.delegate = self;
}  

并实现委托方法以在按钮被点击时得到通知。

- (void)secondViewController:(SecondViewController *)controller didTappedOnButton:(UIButton *)button
{
    // do somthing after button tapped
    // you can get the button title from button.titleLabel.text
}

0

要访问父类的方法或属性,你必须实现一个协议,并使用它的代理。你可以使用在当前(父)类中创建的子类对象来访问子类的方法/属性。但是,你如何从子类访问父类实体呢?是的,通过实现协议。

或者,新手的方式:在点击按钮后,将所需的值保存到NSUserDefaults中。然后,在你转到父类(viewController 1)时,在viewWillAppear中检查保存的值,如果不为空,则显示它。


0
[self.navigationController popViewControllerAnimated:YES];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接