2016-07-24 81 views
1

我在得到的东西从我的UIPopoverPresentationController回失败设立即使协议和委托尝试。斯威夫特:UIPopoverPresentationControllerDelegate委托变成零

我既包括自定义委托(SavingViewControllerDelegate)和UIPopoverPresentationControllerDelegate在我的控制器将调用酥料饼。用户将点击一个正在调用我的控制器中的函数的UIBarButton。在控制器中,我打开酥料饼的编程:

 let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil) 
     let vc = storyboard.instantiateViewControllerWithIdentifier("PopoverProfileViewController") as! ProfileViewController 
     vc.modalPresentationStyle = UIModalPresentationStyle.Popover 
     let popover: UIPopoverPresentationController = vc.popoverPresentationController! 
     popover.barButtonItem = sender as? UIBarButtonItem 
     popover.delegate = self 
     self.presentViewController(vc, animated: true, completion:nil) 
在此视图控制器

,我有这个功能

func sendLoginStatus(status : Bool) { 
    print("LoginStatus") 
    print(status) 
} 

在酥料饼的视图控制器,我添加了一个协议:

protocol SavingViewControllerDelegate 
{ 
    func sendLoginStatus(status : Bool) 
} 

我还在func sendLoginStatus(status:Bool)中添加了一个突破,它返回“委托SavingViewControllerDelegate?一些”​​。

在ProfileViewController:

class ProfileViewController: UIViewController { 
    var delegate : SavingViewControllerDelegate? 

当用户点击一个按钮,一个bool值应发送回呼叫控制器。

@IBAction func logoutButton(sender: AnyObject) { 
    print("sendStatus") 
    delegate?.sendLoginStatus(true) 
    dismissViewControllerAnimated(true, completion: nil) 
} 

我在代表补充断点?.sendLoginStatus(真),它返回 “委托SavingViewControllerDelegate?”是零。 sendLoginStatus从不被调用。

回答

1

您从UIPopoverPresentationController使用委托和预期从自己的协议结果。

而不是设置酥料饼委托符合协议UIPopoverPresentationControllerDelegate你应该创建一个参考,以自己的委托:

let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil) 
let vc = storyboard.instantiateViewControllerWithIdentifier("PopoverProfileViewController") as! ProfileViewController 

// Setting the SavingViewControllerDelegate 
vc.delegate = self 
vc.modalPresentationStyle = UIModalPresentationStyle.Popover 

let popover: UIPopoverPresentationController = vc.popoverPresentationController! 
popover.barButtonItem = sender as? UIBarButtonItem 

// Setting the UIPopoverPresentationControllerDelegate 
popover.delegate = self 

self.presentViewController(vc, animated: true, completion:nil) 

现在,您可以使用自己的委托功能和UIPopoverPresentationController委托功能:

extension YourClass : UIPopoverPresentationControllerDelegate { 
    // All functions of the UIPopoverPresentationControllerDelegate you wish to use 
} 

extension YourClass : SavingViewControllerDelegate { 
    func sendLoginStatus(status : Bool) { 
     // Code 
    } 
} 

旁注1:为防止代表保留周期,我建议您使用weak var delegate: SavingViewControllerDelegate?而不是仅仅是var ~~

旁注2:这是常见的做法还包括一个发送者在委托功能:

protocol SavingViewControllerDelegate { 
    func sendLoginStatus(sender: ProfileViewController, status : Bool) 
} 
+0

谢谢你,现在它的工作!但是,如果我将委托变量设置为弱,那么“弱”可能只适用于类和类绑定的协议类型,而不是“SavingViewControllerDelegate”。 – MJaap

+0

添加:向您的协会提供课程;) – Emptyless