从不同视图通过按钮更新标签

1 sdk uibutton uilabel ios4 ios

如何在按钮点击时更新标签,当它们都在uiview控制器的不同类中时......单击按钮时,标签应该更新...我尝试了很多次..但它没有发生..

还有一个问题是我的应用程序在模拟器中运行良好但是当我在设备上运行时,动态创建的按钮(按钮图像)不可见,动作正在执行但图像丢失..我知道为什么?

Ere*_*şel 7

在iOS中,有几种方法可以维护视图(实际上是视图控制器)之间的通信.对我来说最容易发送通知.您在要进行更改的视图中添加通知的观察者,并从触发更改的视图中发布通知.通过这种方式,您可以从ViewController B告诉ViewController A "已准备就绪,进行更改"

当然,这需要创建接收器视图并且已经在监听通知.

在ViewController B中(发送者)

- (void)yourButtonAction:(id)sender
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"theChange" object:nil];
}
Run Code Online (Sandbox Code Playgroud)

在ViewController A(接收器)中添加观察者以侦听通知:

- (void)viewDidLoad
{
    //.........
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(makeTheChange) name:@"theChange" object:nil];
}
Run Code Online (Sandbox Code Playgroud)

不要忘记将其删除(在这种情况下,打开dealloc)

- (void)dealloc
{
     [[NSNotificationCenter defaultCenter] removeObserver:self name:@"theChange" object:nil];
     [super dealloc];
}
Run Code Online (Sandbox Code Playgroud)

最后,这个方法将更新您的标签

- (void)makeTheChange
{
    yourLabel.text = @"your new text";
}
Run Code Online (Sandbox Code Playgroud)