2016-09-22 24 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的類框架中?

相關問題