【问题标题】:iOS Swift Programmatically Trigger button from previous ViewControlleriOS Swift 以编程方式从以前的 ViewController 触发按钮
【发布时间】:2015-10-23 12:33:52
【问题描述】:

当触发 BackgroundClicked 时,返回前一个视图控制器并以编程方式单击加载时前一个视图控制器上的按钮。但前提是从子视图控制器中单击了 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 在根控制器的负载上单击。我不确定该怎么做,或者是否有可能

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    您可以在按下按钮进入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 示例项目了解更多信息。

    希望这会有所帮助。

    【讨论】:

    • 很高兴为您提供帮助..:)
    【解决方案2】:

    所以这将回到根视图控制器,但你想做的是你想在前一个视图控制器中创建一个函数。在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
    
    } 
    

    【讨论】:

    • viewDidLoad 使用导航控制器导航将不会再次调用。
    猜你喜欢
    • 1970-01-01
    • 2015-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    • 2015-08-16
    相关资源
    最近更新 更多