【问题标题】:How to perform action before triggering exit segue?如何在触发退出 segue 之前执行操作?
【发布时间】:2015-04-09 23:13:18
【问题描述】:

我已经创建了一个从视图控制器 A 到视图控制器 B 的 segue(当前模态),它通过视图控制器 A 的导航控制器中的按钮触发。接管的模态用于通过键入发送朋友请求一封电邮。当用户输入电子邮件并按下按钮提交好友请求时,我想执行由按钮触发的操作(调用服务器发送好友请求,如果电子邮件存在则返回成功,如果电子邮件不存在则返回错误不存在)。如果成功,我想退出/展开segue回到A。如果错误,我不想退出/展开segue。

我已经研究了this 问题,但它似乎没有实现我所需要的。我正在尝试以下方法:

class BViewController: UIViewController {
    // The button function
    @IBAction func sendFriendRequest(sender: AnyObject) {
        println("Button Function.")
        self.performSegueWithIdentifier("SendFriendRequest", sender: self)
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "SendFriendRequest" {
            println("Preparing for segue.")
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

然后在第一个视图控制器中:

AViewController: UIViewController {
    // The unwind function
    @IBAction func saveFriendRequest(segue:UIStoryboardSegue) {
        println("Finished the segue.")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

这是我为按钮设置退出 segue 时的结果(在 ViewController 中按住 ctrl 并拖动按钮到“退出”),我按以下顺序获得调用:

Preparing for segue.
Finished the segue.
Button Function.

但是,我不一定要每次都调用 prepareForSegue 或 unwind 函数,只要服务器给出成功消息。那么我将如何连接情节提要中的内容,以便在调用 performSegueWithIdentifier 时不必调用其他函数(prepareForSegue 等)?

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    从按钮中删除退出转场,而只需将按钮链接到新的 IBAction 并插入

    self.dismissViewControllerAnimated(true, completion: nil)
    

    因此,您的新代码将是:

    @IBAction func saveFriendRequest(sender: AnyObject) {
       //Do your stuff to save the friend request
       self.dismissViewControllerAnimated(true, completion: nil)
    }
    

    【讨论】:

    • 感谢您的帮助,这正是我所需要的!
    【解决方案2】:

    如果要在segue之前执行action,创建if-statement来判断action是否成功完成,然后执行segue。即。

    if (ActionSuccess) {
    self.performSegueWithIdentifier("Segue", sender: nil)
    }
    

    【讨论】:

    • 是的,这将是需要的,很抱歉没有澄清这一点。如何在不将按钮附加到视图控制器上的出口的情况下使 segue 工作,因为通过附加它,它会在执行按钮操作之前执行 prepareForSegue 并展开?
    猜你喜欢
    • 2012-12-11
    • 1970-01-01
    • 1970-01-01
    • 2022-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多