问题描述
我的故事板中有两个 UIViewConrollers:MainViewController 和 SecondViewController.当用户点击一个名为 Show Popover 的按钮时,我将把 SecondViewController 显示为一个弹出框:
There are two UIViewConrollers in my Storyboard: MainViewController and SecondViewController. I'm going to show SecondViewController as a popover when user taps a button called Show Popover:
//MainViewController
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if segue.identifier == "GoToSecondViewControllerSegue"
{
var vc = segue.destinationViewController as! SecondViewController
var controller = vc.popoverPresentationController
if controller != nil
{
controller?.delegate = self
vc.inputTextDelegate = "I'm a popover!"
}
}
}
func popoverPresentationControllerDidDismissPopover(popoverPresentationController: UIPopoverPresentationController) {
println("done")
}
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle
{
return .None
}
//SecondViewController
@IBAction func dismissPopover(sender: UIButton) {
dismissViewControllerAnimated(true, completion: nil)
//This dismisses the popover but does not notify the MainViewConroller
}
segue 的锚点连接到一个按钮上:
The anchor of segue is connected to a button:
现在我有两个问题:
当我点击弹出框内的取消按钮时,它会关闭弹出框,但不会触发 MainViewController
如何将数据从 SecondViewController 传递到 MainViewController,例如 UITextView 的文本值.
How can I pass data from the SecondViewController to the MainViewController, text value of a UITextView for example.
推荐答案
协议和委托是解决此类问题的方法.就我而言,我定义了一个协议并使 MainViewController 符合该协议.
Protocols and delegations are solution to such problems. In my case I defined a protocol and conformed the MainViewController to the protocol.
//SecondViewController
protocol MyDelegate{
func DoSomething(text:String)
}
class SecondViewController: UIViewController {
var delegate:GetTextDelegate?
var inputTextDelegate:String = ""
override func viewDidLoad() {
newText.text = inputTextDelegate
}
@IBAction func dismissPopover(sender: UIButton) {
dismissViewControllerAnimated(true, completion: nil)
//This dismisses the popover but does not notify the MainViewConroller
}
@IBAction func doneButtonAction(sender: UIButton) {
if let delegate = self.delegate {
delegate.DoSomething(newText.text)
self.dismissViewControllerAnimated(true, completion: nil)
}
}
}
class MainViewController: UIViewController, UIPopoverPresentationControllerDelegate, MyDelegate {
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if segue.identifier == "GoToSecondViewControllerSegue"
{
var vc = segue.destinationViewController as! SecondViewController
vc.delegate = self
vc.inputTextDelegate = "I'm a popover!"
}
}
func popoverPresentationControllerDidDismissPopover(popoverPresentationController: UIPopoverPresentationController) {
//...
}
func DoSomething(text: String) {
//Do whatever you want
println(text)
}
}
这篇关于Swift:弹出窗口关闭回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!