我如何“检查”ViewController是否具有指定var?
@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 :(得分:1)
您无法检查对象是否具有某个成员变量,只有它可以转换为某种类型。一旦你知道它可以被转换为某种类型,你就可以确定它是否有一个成员变量。
你可以这样做一个可选的演员:
if let specialVc = vc as? SpecialViewController {
// use specialVc.specialVar
}
else {
// the view controller could not be cast so it does not have specialVar
}
如果您更喜欢使用协议,也可以使用协议。