[英]Add a “Done” button to dismiss a programmatically created UIViewController
我是一個快速的新手,並制作了一個演示應用程序,在故事板中有一個UIViewController和UITableViewController。 UIViewController有一個Collection View和一個嵌入式導航控制器。 在點擊集合視圖單元格時,應用程序將轉到UITableViewController。 我也可以從UITableViewController回到我的UIViewController。 這一切都運作良好。 現在,我的UITableViewController中的一些行有URL。 在點擊URL時,我以編程方式在UIviewcontroller中創建webview並獲取要加載的URL。 問題是我無法關閉webview並在此之后返回到我的UITableViewController。 這是我在UITableViewController類中的代碼:
// When user taps a row, get the URL and load it in a webview
let mywebViewController = UIViewController()
let webView = UIWebView(frame: mywebViewController.view.bounds)
webView.loadRequest(NSURLRequest(URL: url)) // url from the row a user taps
mywebViewController.view = webView
self.navigationController!.presentViewController(mywebViewController, animated: true, completion: nil)
如何向這個以編程方式創建的UIviewcontroller添加“完成”按鈕以關閉webview並返回到我的UITableViewController
您可以將mywebViewController
包裝在UINavigationController
然后將rightBarButtonItem
為UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "dismiss")
如下所示:
let navController = UINavigationController(rootViewController: mywebViewController)
mywebViewController.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "dismiss")
self.navigationController!.presentViewController(navController, animated: true, completion: nil)
並在UITableViewController
添加一個dismiss
函數:
func dismiss() {
self.dismissViewControllerAnimated(true, completion: nil)
}
將完成按鈕添加到您呈現的ViewController並為其執行操作。 要解雇ViewController,請嘗試以下方法:
self.dismissViewControllerAnimated(true, completion: nil)
在mywebViewController
和@IBAction
中調用添加按鈕
self.dismissViewControllerAnimated(true, completion: nil)
你可以做一件事。
當您將mywebViewController
推mywebViewController
導航控制器時,請使導航欄可見。
只需點擊導航欄中的“返回”按鈕,即可輕松關閉mywebViewController
。
希望這對你有所幫助。 :)
Swift 4和5的更新
在你導航的VC中
navController.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.dismiss))
必須將您的選擇器聲明為@objc函數
@objc func dismiss(){
self.dismiss(animated: true)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.