【问题标题】:How to Update Label From Different View Controller using NSUserDefaults如何使用 NSUserDefaults 从不同的视图控制器更新标签
【发布时间】:2014-03-08 22:05:32
【问题描述】:

我正在尝试通过按下不同视图控制器 2 上的按钮来更新视图控制器 1 上的标签。我在视图控制器 2 中有此 IBAction:

- (IBAction)done:(id)sender {

    DropPinVC * vc = [[DropPinVC alloc]init];

    NSString *updatedLabel = [[NSUserDefaults standardUserDefaults] stringForKey:@"Type Location"];

    NSLog(@"Updated Label = %@", updatedLabel);

    vc.TypeLabel.text = updatedLabel;

    [self closeScreen];
}

但是,视图控制器 1 上的标签不会更新。有人知道这个问题的解决方案吗?

【问题讨论】:

    标签: ios uiviewcontroller label nsuserdefaults ibaction


    【解决方案1】:

    vc 是在发布的操作范围内声明的 DropPinVC 类的新实例,与您要更新的实例不同。 p>

    实现此目的的一种方法是保留指向第一个视图控制器的指针。

    为了让 viewController2(vc2) 更新 viewController1(vc1) 拥有的 UILabelvc2 strong> 需要对 vc1 的引用,以便它可以访问标签。

    将属性添加到 DropPinVC

    类型的 vc2
    @property (nonatomic, strong) DropPinVC *vc1Ref;
    

    假设 vc1 分配并初始化 vc2,然后在这之后分配 vc1Ref 属性。

    vc2.vc1Ref = self;
    

    现在在 IBAction 中,您的代码现在可以访问正确的实例并更新正确的标签。

    - (IBAction)done:(id)sender {
    
    NSString *updatedLabel = [[NSUserDefaults standardUserDefaults] stringForKey:@"Type Location"];
    
    NSLog(@"Updated Label = %@", updatedLabel);
    
    self.vc1Ref.TypeLabel.text = updatedLabel;
    
    [self closeScreen];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-08
      • 2011-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-09
      • 1970-01-01
      • 2016-12-17
      相关资源
      最近更新 更多