如何通过同一子视图(UIViewController)内的按钮来关闭子视图

时间:2015-12-08 13:25:53

标签: ios swift uiview swift2

我有2个UIViewControllers。第一个ViewController有一个标签,视图和一个按钮,第二个视图有一个标签,文本框和添加按钮,底部是ok按钮。两个ViewControllers都有单独的swift文件。当我按下第一个ViewController中的按钮时,它将第二个视图控制器显示为子视图。在子视图中一切正常

但是当我按下确定按钮时,我想要解除子视图。我在谷歌搜索但我找不到任何相对答案。

注意:我使用的是Xcode 7.1.1 swift2。 “取消”按钮必须放在子视图中。

用于将第二个视图显示为子视图的代码

    let object = self.storyboard?.instantiateViewControllerWithIdentifier("caller") as? ViewController
    self.view.addSubview(object!.view)

here caller - 2nd viewController StoryBoard ID。 ViewController - 第二个ViewController

3 个答案:

答案 0 :(得分:0)

我认为不是将第二个viewcontroller的视图添加为第一个viewcontroller的子视图,而是你应该(甚至可能想要)做的事情如下:

在你的第一个viewcontroller中呈现第二个viewcontroller:

let vc2 = self.storyboard?.instantiateViewControllerWithIdentifier("caller")
presentViewController(vc2!, animated: true, completion: nil)

在你的第二个viewcontroller中解散第一个viewcontroller:

dismissViewControllerAnimated(true, completion: nil)

答案 1 :(得分:0)

您有3个选项 1.在按钮操作方法的第二个视图控制器中添加此行self.dismissViewControllerAnimated(true, completion: nil)

缺点:通常视图控制者不是解雇他的人

专业人士轻松

  1. 如果您使用的是Swift,可以尝试添加完成处理程序: 在第二个ViewController中添加这个 var completionHandler: (() -> Void)? = nil 在您称之为self.completionHandler?()
  2. 的操作中

    在初始化第二个视图后的第一个视图中,你可以用它来采取行动

    secondViewController.completionHandler = {
    secondViewController.dismissViewControllerAnimated(true, completion: nil)
    }
    

    专业人士我喜欢闭包

    缺点:尚未找到

    1. 您可以使用委托方法 专业人士:代表 缺点:我喜欢关闭更多
    2. 仅供参考由于您没有告诉我们您如何展示您的观点,我的解决方案已经完成,假设您使用presentViewController进行展示

      <强>更新

      我看到你更新了你的问题,在这种情况下,方法nr 2.是一个只能改变这个

      object.completionHandler = {
          object.view.removeFromSuperview()
      }
      

      我想添加的唯一内容是不要将ViewController添加为子视图,为此使用UIView

答案 2 :(得分:0)

用于显示当前视图控制器

let presentVC = FirstViewController(); self.navigationController?.presentViewController(presentVC, animated: true, completion: nil)

并且在&#34; SecondViewController&#34;按钮单击操作

self.dismissViewControllerAnimated(true, completion: nil)

我认为这会奏效。