我肯定我错过了一些相当愚蠢的东西,我一直都能做类似的事情,但似乎不是这次。
我有两个类,第一个类是UIView并且有一个默认为false的变量。第二个类是一个UIViewController,所以我试着简单地在第二个类中设置变量,那不起作用。
我正试图使用一个可以简单地返回我想要的协议,如果你能告诉我为什么值为nil,我会很感激。我的协议的实现有什么问题?
第一课:
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
}
}
那么在第二类我做;
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,而不是控制器。
另外,我已经看到了实现协议的建议,因为我正在努力做到这一点,似乎我错过了一些东西。感谢任何评论。谢谢。
您在这里使用了许多没有实例化位置的变量。请张贴所有相关代码,而不仅仅是片段:)你使用calendarDayView
, firstClass
,但只有customClass
的声明,所以没有办法知道他们发生了什么。
我看到的一个问题是试图让这个:print("testing", test )
工作。
看起来你正在这里创建视图:
lazy var customclass: FirstClass = {
let dv = FirstClass()
//I tried setting it true here
dv.myParam = true
return dv
}
但是你从来没有设置委托,考虑到你试图在构造函数中打印activatcustomization的结果,委托不可能有一个值,除非它之前在初始化器中设置过。
是可能的,你的意思是添加到类的框架在一个didSet?