如果我返回Swift

时间:2016-12-30 12:45:13

标签: ios swift uistoryboardsegue

我会给出一个我想要的例子,所以它并不那么令人困惑:

示例:

让我们说每次我的用户动态滚动3个注释时,我都会添加一个地图。现在我在地图下面有一个按钮,当我按下它时,我转到另一个viewController做我想做的事情,然后回到带有地图的viewController,现在我想找到我的地图有的所有注释,而不是重新加载视图所有

我曾经使用过这个在viewControllers之间移动的函数:

func move(identifier: String , viewController : UIViewController) -> Void {
    let mstoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let vc: UIViewController = mstoryboard.instantiateViewControllerWithIdentifier(identifier) 
    viewController.presentViewController(vc, animated: true, completion: nil)
}

我也试过这个:

let vc = self.storyboard?.instantiateViewControllerWithIdentifier("view") as? MyViewcontroller
         self.presentViewController(vc!, animated: true, completion: nil)

当我使用它们时,显示的viewcontroller正在调用viewDidload,因此它就像第一次出现一样。

另一个例子是tabBarViewController如果您注意到在导航标签时没有任何重新加载(只有被调用的函数是viewDidAppear

修改

test file

2 个答案:

答案 0 :(得分:2)

问题是由于地图控制器在导航回另一个控制器时被取消分配,另一个是在您想再次移动到地图屏幕时创建的。

您需要的是保持同一个控制器实例并呈现该实例。在演示控制器中保留强大的参考就足够了。

class PresentingController {
    // making the property lazy will result in the getter code
    // being executed only when asked the first time
    lazy var mapController = { () -> UIViewController in
        let mstoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        return mstoryboard.instantiateViewControllerWithIdentifier("mapControllerIdentifier")
    }()

    func moveToMap() {
        // simply use the mapController property
        // the property reference will make sure the controller won't
        // get deallocated, so every time you navigate to that screen
        // you'll get the same controller
        presentViewController(mapController, animated: true, completion: nil)
    }
}

答案 1 :(得分:1)

根据你发布的同一个项目,你从 view 2 回到 view 1 时实例化了一个新的UIViewController,这就是为什么你的{{再次调用1}}并重新加载整个地图视图。

在您的示例项目中,而不是

viewDidLoad

您只需在按下按钮时关闭视图2

lazy var mapController2 = { () -> UIViewController in
    let mstoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    return mstoryboard.instantiateViewController(withIdentifier: "first")
}

当您展示新的@IBAction func butto(_ sender: AnyObject) { //Your initial code //PresentingController().moveToMap(self, flag: 1) self.dismiss(animated: true, completion: nil) } 时,较旧的UIViewController不会从内存中移除,而是隐藏在新的UIViewController后面。因此,无论何时您希望返回到保持以前状态的UIViewController,您只需关闭新的UIViewController

然而,如果您正在执行第二个UIViewController上要执行的某些任务,并希望在初始UIViewController中反映出来,则必须设置闭包更新您的初始UIViewController