问题描述
我有两个视图,其中一个带有标签.在第二个视图上,有一个按钮.我在这里想要实现的是能够按下按钮,它会在第一个视图上更新标签.我怎么做?我无法从第二个视图访问IBOutlet.我需要对IBOutlet进行公开公开等吗?
I have two views with a label on one of them. On the second view, there is a button. What I want to achieve here is to be able to press the button and it updates the label on the first view. How do I do that? I can't access the IBOutlet from the second view. Is there something that I have to do to the IBOutlet to make it public etc?
推荐答案
您可以为此使用NSNotificationCenter
.
首先在您的viewDidLoad
方法中,将此代码添加到您的firstViewController
类中:
First of all in your viewDidLoad
method add this code in your firstViewController
class:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "refreshlbl:", name: "refresh", object: nil)
在您的应用加载时会显示addObserver
.
which will addObserver
when your app loads.
并在同一viewController
中添加此帮助程序方法.
And add this helper method in same viewController
.
func refreshlbl(notification: NSNotification) {
lbl.text = "Updated by second View" //Update your label here.
}
之后,在您关闭视图时,在secondViewController
中添加以下代码:
After that in your secondViewController
add this code when you dismiss your view:
@IBAction func back(sender: AnyObject) {
NSNotificationCenter.defaultCenter().postNotificationName("refresh", object: nil, userInfo: nil)
self.dismissViewControllerAnimated(true, completion: nil)
}
现在,当您从secondView
按下返回按钮时,将从firstView
调用refreshlbl
方法.
Now when you press back button from secondView
then refreshlbl
method will call from firstView
.
这篇关于在另一个视图上更新标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!