以前ViewController的iOS Swift编程触发按钮

时间:2015-07-31 18:27:36

标签: ios swift

当触发BackgroundClicked时,返回上一个viewcontroller并以编程方式单击加载时上一个viewcontroller上的按钮。但只有从子视图控制器中单击了BackgroundClicked

例如

//this button is on child controller
@IBAction func BackgroundClicked(sender: AnyObject)
{
    self.navigationController?.popToRootViewControllerAnimated(true)
    // when im on the root controller click button abc 
    // button abc resides on the root controller
} 

我只想在单击BackgroundClicked时单击根控制器的加载按钮abc。我不确定如何解决这个问题,或者它是否可能

2 个答案:

答案 0 :(得分:5)

如果按下按钮,您可以在下面的ChildViewController节目中发送通知:

按下按钮时,在ChildViewController中添加此代码:

@IBAction func BackgroundClicked(sender: AnyObject)
{
    NSNotificationCenter.defaultCenter().postNotificationName("refresh", object: nil)
    self.navigationController?.popToRootViewControllerAnimated(true)
} 

ParentViewController中将此代码添加到viewDidLoad方法中:

override func viewDidLoad() {
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "refreshList:", name:"refresh", object: nil)
}

这是你的助手功能:

func refreshList(notification: NSNotification){

    println("parent method is called")
}

现在,当您从ChildViewController refreshList方法按下后退按钮时,将从您的ParentViewController调用。

检查THIS示例项目以获取更多信息。

希望这会有所帮助。

答案 1 :(得分:0)

这样会回到根视图控制器,但是你想要做的是你想在前一个视图控制器中创建一个函数。在viewController中的代码中,您将返回以viewDidLoad()方法运行函数的名称。此外,每当您单击后退按钮时,您想要更改变量的值,因为您不希望每次viewDidLoad()时都运行该函数。这就是前一个视图控制器的代码应该是这样的:

var decideInt: Int = 0

override func viewDidLoad() {
        super.viewDidLoad()

        if decideInt == 0 {
                // Do Nothing
        } else if decideInt == 1 {
                functionYouWantToRun()
                decideInt = 0
        }
}

func functionYouWantToRun() {

        //Write the code to the function you want to run

}

以下是您需要编写的代码:

//this button is on child controller
@IBAction func BackgroundClicked(sender: AnyObject)
{
    self.navigationController?.popToRootViewControllerAnimated(true)
    var goToView: DestinationViewControllerName = DestinationViewControllerName()
    goToView.decideInt = 1

}