gpt4 book ai didi

ios - 在另一个下方的 View Controller 中更新 uilabel

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:09:14 26 4
gpt4 key购买 nike

我有两个 View Controller ,FirstViewController 和 FourthViewController。 FirstViewController 是我的初始 View Controller 。我将 FourthViewController 呈现给

UIViewController *fourthController = [self.storyboard instantiateViewControllerWithID:@"Fourth"];
[self presentViewController:fourthController animated:YES completion:nil];

然后,在 FourthViewController 的 .m 中,我想更改 FirstViewController 中 UILabel 的文本。所以我用

UIViewController *firstController = [self.storyboard instantiateViewControllerWithID:@"First"];
firstController.mainLab.text = [NSMutableString stringWithFormat:@"New Text"];

但是,在我使用之后

[self dismissViewControllerAnimated:YES completion:nil];

我发现我的 mainLab 的文本没有更新。有谁知道为什么吗?

最佳答案

当您从 FourthViewController.m 调用此行时,您实际上是在创建 FirstViewController 的新实例,而不是使用已经创建的实例。

UIViewController *firstController = [self.storyboard 
instantiateViewControllerWithID:@"First"];

您可以通过两种方式解决这个问题。

1) 使用通知

当需要更改标签文本时,从 FourthViewController 发布通知。

[[NSNotificationCenter defaultCenter] postNotificationName:@"updateLabel" 
object:self];

在您的 FirstViewController viewDidLoad 方法中创建一个等待此通知被触发的观察者。

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

实现 updateLabelCalled: 并更新标签。

- (void) updateLabelCalled:(NSNotification *) notification
{
if ([[notification name] isEqualToString:@"updateLabel"]){
//write code to update label
}

}

2) 实现委托(delegate)

已经说明了here在计算器中。基本思想是创建一个 FourthViewController 委托(delegate),并创建一个委托(delegate)方法来更新标签。 FirstViewController 应该实现这个方法。

关于ios - 在另一个下方的 View Controller 中更新 uilabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18200668/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com