将带有委托作为参数的UIViewcontroller传递给swift函数的问题

时间:2015-01-09 11:53:42

标签: ios iphone swift ios8

class func invite(_cntrl : UIViewController) 
{
  // code to open mail composer sheet
}

此方法需要接受符合 MFMailComposeViewControllerDelegate 的控制器。

目前它提供错误

Type 'UIViewController' does not conform to protocol 
'MFMailComposeViewControllerDelegate'

如何通过uiviewconroller符合MFMailComposeViewControllerDelegate

类似的东西:

class func invite(_cntrl : UIViewController<MFMailComposeViewControllerDelegate>)
{
   // code to open mail composer sheet
}

4 个答案:

答案 0 :(得分:0)

我相信如果你将参数类型设置为MFMailComposeViewControllerDelegate,它会接受它。

所以你的功能是:

class func invite(_cntrl : MFMailComposeViewControllerDelegate)

Swift Language Guide

中作为类型的协议中找到

编辑:

进一步说明,因为您希望能够通过也符合MFMailComposeViewControllerDelegate的UIViewController的子类,看来扩展UIViewController类是最好的方法。 (这些就像ObjC类别。

e.g。

extension UIViewController : MFMailComposeViewControllerDelegate
{
  optional func mailComposeController(_ controller: MFMailComposeViewController!,
            didFinishWithResult result: MFMailComposeResult,
                          error error: NSError!)
  {
     self.dismissViewControllerAnimated(flag:true, completion:nil); 
  }
}

答案 1 :(得分:0)

我不知道确切的解决方案。但是,如果您想使用is关键字检查某个对象是否符合该特定协议(也可以使用as),请另行选择 在这种情况下,它看起来像:

class func invite(_cntrl : UIViewController)
{
    if _cntrl is MFMailComposeViewControllerDelegate
    {
        println("Confirms to protocol")
    }
    else
    {
        println("Not confirm")
    }
}

Checking for Protocol Conformance

中提到了这种方法
  

您可以使用“类型转换”中描述的isas运算符进行检查   用于协议一致性,以及转换为特定协议。检查   for和cast to a protocol遵循完全相同的语法   检查并转换为类型:

     

is运算符如果实例符合协议则返回true,如果不符合则返回false

     

downcast运算符的as?版本返回协议类型的可选值,如果实例不符合该协议,则此值为nil

     

ascast运算符的as版本强制downcast为协议类型,如果向下转换不成功则触发运行时错误。

答案 2 :(得分:0)

在Swift 3中你可以这样做

class func invite(_cntrl : MFMailComposeViewControllerDelegate) 
{
   // code to open mail composer sheet
   // You can cast it to a UIViewController subclass if you need it
}

答案 3 :(得分:0)

你可以做点什么,

func setDelegate<T : UIViewController>(controller: T) where T: YourDelegateName{
    delegate = controller
}
相关问题