2014-07-18 41 views
0

如何檢查ViewController是否有指定的變量?檢查UIViewController是否有一個特定的變量

@objc protocol InsetBlurModalSequeProtocol { 
    func getBackgroundImage() -> UIImage 
} 



@objc(InsetBlurModalSeque) class InsetBlurModalSeque: UIStoryboardSegue { 

    override func perform() { 
     var sourceViewController = self.sourceViewController as UIViewController 
     let destinationViewController = self.destinationViewController as UIViewController 

     // Make sure the background is ransparent 
     destinationViewController.view.backgroundColor = UIColor.clearColor() 

     var image:UIImage? 
     if sourceViewController is InsetBlurModalSequeProtocol { 
      // Use secial background plate 
      image = InsetBlurModalSequeProtocol(sourceViewController).getBackgroundImage() // Error 'InsetBlurModalSequeProtocol' is not constructible with '@lvalue UIViewController' 
     } 
     else { 
      // Take screenshot from source VC 
      UIGraphicsBeginImageContext(sourceViewController.view.bounds.size) 
      sourceViewController.view.drawViewHierarchyInRect(sourceViewController.view.frame, afterScreenUpdates:true) 
      image = UIGraphicsGetImageFromCurrentImageContext() 
      UIGraphicsEndImageContext() 
     } 
+0

[specialvar className] isMemberOfClass:[yourClass class]? –

回答

1

您不能檢查,如果一個對象具有一定的成員變量,只有當它可以轉換爲某種類型。一旦你知道它可以被轉換成某種類型,你肯定知道它是否有一個成員變量。

你可以做一個可選的鑄像這樣:

if let specialVc = vc as? SpecialViewController { 
    // use specialVc.specialVar 
} 
else { 
    // the view controller could not be cast so it does not have specialVar 
} 

你也可以,如果你喜歡的是在一個完整的類上使用的協議。

+0

嗯......我只有新的類是一個ViewController。但其中一些是「特殊」並有一定的變數。我該如何檢測那些特殊變量的「特殊類」。 – fabian

+0

@fabian,沒有辦法在Swift中「檢測」它。您需要知道特殊變量在其上定義的子類/協議。 – drewag

+0

我試圖與協議一起工作,並試圖做自我反省。問題:無法從'UIViewController'降級爲非@ objc協議類型'MyProtocol' – fabian

相關問題