通过不同视图的按钮更新标签 [英] Update a label through button from different view
问题描述
当它们都在不同类的 uiview 控制器中时如何通过按钮单击更新标签...单击按钮时,标签应该更新...我尝试了很多次..但它没有发生..
How to update a label by button clicks when they both are in different classes of uiview controller...when button is clicked,the label should be update...i tried many times..but its not happening..
还有一个问题是我的应用在模拟器中运行良好,但是当我在设备上运行时,动态创建的按钮(按钮图像)不可见,动作正在执行但图像丢失..我知道为什么吗?
one more Question is my app is running good in simulator but when i run on device the dynamically created button(button image) is not visible,action is performing but image is missing..may i know why?
推荐答案
有几种方法可以在 iOS 中保持视图(实际上是视图控制器)之间的通信.对我来说最简单的是发送通知.您在要进行更改的视图中为通知添加观察者,然后从将触发更改的视图中发布通知.这样你就可以从 ViewController B 告诉 ViewController A 东西准备好了,做出改变"
There are a few ways to maintain communication between views (view controllers, actually) in iOS. Easiest of which for me is sending notifications. You add an observer for a notification in the view you want to make the change, and from the view that will trigger the change, you post the notification. This way you tell from ViewController B to ViewController A that "something is ready, make the change"
当然,这需要您创建接收器视图并且已经在监听通知.
This, of course, requires your receiver view to be created and already be listening for the notification.
在 ViewController B(发送者)中
In ViewController B (sender)
- (void)yourButtonAction:(id)sender
{
[[NSNotificationCenter defaultCenter] postNotificationName:@"theChange" object:nil];
}
在 ViewController A (receiver)添加观察者来监听通知:
In ViewController A (receiver) Add the observer to listen for the notification:
- (void)viewDidLoad
{
//.........
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(makeTheChange) name:@"theChange" object:nil];
}
不要忘记删除它(在这种情况下,在 dealloc
上)
Do NOT forget to remove it (in this case, on dealloc
)
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"theChange" object:nil];
[super dealloc];
}
最后,更新标签的方法
- (void)makeTheChange
{
yourLabel.text = @"your new text";
}
这篇关于通过不同视图的按钮更新标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!