2016-09-22 75 views
0

我确信我错过了一些非常愚蠢的事情,我总是能够像这样做类似的事情,但似乎不是这次。如何在这种情况下使用协议来更改以编程方式添加的uiview中的变量?

我有两个类,第一类是UIView,并有一个变量默认为false。第二个类是一个UIViewController,所以我试着简单地在第二个类中设置变量,但不起作用。

我想使用一个协议,它可以简单地返回我想要的东西,如果能告诉我为什么值为零,我将不胜感激。基本上执行我的协议有什么问题?

头等舱:

protocol CustomizationDelegate{ 
    func activateCustomization() -> Bool? 
} 

class FirstClass: UIView, UICollectionViewDelegate, UICollectionViewDataSource , UICollectionViewDelegateFlowLayout{ 


    var modeDelegate: CustomizationDelegate? 



    var myParam = false 


//where I try to print my boolean to the console and I get nil 

override init(frame: CGRect) { 
    super.init(frame : CGRect(x: 0, y: 0, width: 200, height: 400)) 
    //logging to console 
let test = self.modeDelegate?.activateCustomization() 
    print("testing", test) 
    self.initialSetup() 
} 


fun initial setup(){ 
... initialization 
} 

} 

然后在第二I类做;

import UIKit 
import Firebase 

//implementing the protocol 
class SecondClass: UIViewController, CustomizationDelegate { 


// the first class 
lazy var customclass: FirstClass = { 
    let dv = FirstClass() 

    //I tried setting it true here 
    dv.myParam = true 

    return dv 
}() 


func activateCustomization() -> Bool? { 
     return true 
    } 

override func viewDidLoad() { 
    super.viewDidLoad() 

//setting the delegate to self 
calendarDayView.modeDelegate = self 

firstClass.frame = CGRect(x: 0, y: 40, width: srvceSetupWindow.frame.width, height: srvceSetupWindow.frame.height-80) 

//adding fist class as a subview; seems fine except that myParam is still the default ; false 
self.addSubview(calendarDayView) 


enter code here 
...other codes 
} 
} 

我已经看到了SO的建议,首先如果它是一个亲子关系,我可以使用一个简单的父母!检查获得相同的实例,但似乎我不能因为第一类是UIView而不是控制器。

此外,我已经看到了实施协议的建议,因为我正在努力做到这一点,似乎我错过了一些东西。欣赏任何评论。谢谢。

回答

0

您在这里使用了很多变量,而没有实例化它们的位置。请发布所有相关的代码,而不仅仅是片段:)你使用calendarDayView,firstClass,但只有customClass的声明,所以没有办法知道他们正在发生什么。

我看到的一个问题是试图得到这个:print("testing", test)工作。

它看起来像你在这里创建视图:

lazy var customclass: FirstClass = { 
    let dv = FirstClass() 

    //I tried setting it true here 
    dv.myParam = true 

    return dv 
} 

但你从来没有设置委托,并考虑你要打印activateCustomization的结果,在构造函数中,这是不可能的除非先前在初始化程序中设置,否则委托将具有值。

是否有可能将您添加到didSet的类框架中?

相关问题