[英]how to dismiss a subview by a button inside the same subview which is a UIViewController
我有2個UIViewControllers。 第一個ViewController有一個標簽,視圖和一個按鈕,第二個視圖有一個標簽,文本框和添加按鈕,並在底部的ok按鈕。兩個ViewController都有單獨的swift文件。 當我按下第一個ViewController中的按鈕時,它將第二個視圖控制器顯示為子視圖。 在子視圖中,一切正常
但是當我按下確定按鈕時,我希望子視圖被關閉。我在谷歌上搜索,但找不到任何相對答案。
注意:我正在使用Xcode 7.1.1 swift2。 “取消”按鈕必須放在子視圖中。
用於將第二個視圖顯示為子視圖的代碼
let object = self.storyboard?.instantiateViewControllerWithIdentifier("caller") as? ViewController
self.view.addSubview(object!.view)
在這里調用者-第二個viewController StoryBoard ID。 ViewController-第二個ViewController
我認為不是將第二個viewcontroller的視圖添加為第一個viewcontroller的子視圖,而是執行以下操作(甚至可能想要做):
在您的第一個ViewController中顯示第二個ViewController:
let vc2 = self.storyboard?.instantiateViewControllerWithIdentifier("caller")
presentViewController(vc2!, animated: true, completion: nil)
在第二個ViewController中關閉第一個ViewController:
dismissViewControllerAnimated(true, completion: nil)
您有3個選項1.在按鈕操作方法的第二個視圖控制器中,添加以下行self.dismissViewControllerAnimated(true, completion: nil)
缺點:通常,視圖控制器不是負責其解雇的人
優點:簡單
var completionHandler: (() -> Void)? = nil
var completionHandler: (() -> Void)? = nil
在您這樣調用的動作中為self.completionHandler?()
在第二個視圖初始化之后的第一個視圖中,您可以使用它來執行操作嗎?
secondViewController.completionHandler = {
secondViewController.dismissViewControllerAnimated(true, completion: nil)
}
優點:我喜歡閉包
缺點:尚未找到
僅供參考,因為您沒有告訴我們如何展示視圖,所以假設您使用presentViewController
來展示我的解決方案
更新
我看到您更新了問題,在這種情況下,方法nr 2是唯一可以更改的方法。
object.completionHandler = {
object.view.removeFromSuperview()
}
我唯一想添加的內容是不添加ViewController作為子視圖,為此您可以使用UIView
用於顯示當前視圖控制器
let presentVC = FirstViewController(); self.navigationController?.presentViewController(presentVC, animated: true, completion: nil)
然后在“ SecondViewController”按鈕上單擊操作
self.dismissViewControllerAnimated(true, completion: nil)
我認為這會起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.