Xcode - 从不同视图更新ViewController标签文本

时间:2012-04-07 07:16:36

标签: iphone objective-c uilabel

我的项目ViewControllerSettingsView中有两个视图控制器。在这里,当我点击ViewController's后退按钮时,我正在尝试更新SettingsView's标签。 NSLog工作正常,但标签没有更新...... 请帮帮我......

SettingsView.m

-(IBAction)backToMain:(id) sender {

  //calling update function from ViewController
    ViewController * vc = [[ViewController alloc]init];
    [vc updateLabel];
    [vc release];

  //close the SettingsView 
    [self dismissModalViewControllerAnimated:YES];
}

ViewController.m

- (void)updateLabel
{
    NSLog(@"Iam inside updateLabel");
   self.myLabel.text = @"test";
}

你能否告诉我我的代码有什么问题?谢谢!

4 个答案:

答案 0 :(得分:9)

您必须为此实施协议。请遵循:

1)在SettingView.h中定义这样的协议

 @protocol ViewControllerDelegate

 -(void) updateLabel;

  @end

2)在.h类中定义属性并在.m类中定义..

    @property (nonatomic, retain) id <ViewControllerDelegate> viewControllerDelegate;

3)在SettingsView.m IBAction

  -(IBAction)backToMain:(id) sender 
 {
     [viewControllerDelegate updateLabel];
 }

4)在ViewController.h中采用这样的协议

@interface ViewController<ViewControllerDelegate>

5)在viewController.m中包含viewDidLoad

中的这一行
settingView.viewControllerDelegate=self

答案 1 :(得分:1)

您的标签未更新,因为您尝试使用新实例调用updateLabel方法。

您应该调用已提供模态视图的viewcontroller原始实例的updateLabel

你可以使用委托机制或NSNotification来做同样的事情。

委托机制会很干净。 NSNotification快速而肮脏。

答案 2 :(得分:0)

您并未正确调用正确的vc。这是因为您正在创建该类的新实例并调用该实例的updateLabel

您有几个选择。

  1. 将它实现为delegate callBack(委托messagePassing或委托通知 - 但是你想调用它)来通知该类实例调用updateLabel方法。

  2. 将原始实例VC用作dependency injection到您当前所在的班级,并使用该实例调用updateLabel

  3. 使用NSNotifications / NSUserDefaults在viewControllers之间进行通信,并为您的操作设置通知系统。这很容易,但从长远来看并不是很好。

  4. 我会推荐选项1(或)选项2.

答案 3 :(得分:0)

只需在SettingsView类中声明:

 UILabel *lblInSettings;// and synthesize it

现在,在演示设置viewController:

时,如下所示进行分配
settingsVC.lblInSettings=self.myLabel;

然后无论你在lblInSettings中更新它显然都会出现在MainView中.... 不需要任何委托方法或更新方法。

Means if you assign at the time of dismissing like
lblInSettings.text=@"My new value";
then self.myLabel also will be updated.

如果您有任何疑问,请告诉我?

相关问题