在Swift UIView XIB中全局初始化变量为'nil'?

时间:2016-11-29 07:43:46

标签: ios swift uiview xib

我在UIView类中全局初始化了变量。

变量statusLabel为字符串。我在Pickerview statusLabel委托方法中为didSelectRow分配了一个值。 在那里我得到了字符串的价值。但是,当委托完成字符串更改的值为nil

对于所有其他全局初始化变量,它都是相同的。 可能是什么原因?

先谢谢

class CustomPickerMenu: UIView,UIPickerViewDataSource,UIPickerViewDelegate
{
    var statusLabel = String()

    var pickerArray = [String]()

    required init?(coder aDecoder: NSCoder)
    {
        pickerArray = ["None","Connections","All"]
        super.init(coder: aDecoder)
         print("Awake with coder")

    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
    {
        if(row == 0)
        {
            statusLabel = pickerArray[row]
        }
        if(row == 1)
        {
            statusLabel = pickerArray[row]
        }
        if(row == 2)
        {
            statusLabel = pickerArray[row]
        }
      print("statusLabel : " + statusLabel)
    }

    @IBAction func saveStatus(_ sender: Any)
    {   
        delegate?.statusChange(controller: self, text:statusLabel)
        self.delegate?.showNavigationController(controller: self)

        print("statusLabel : " + statusLabel)
    }

这里是didselectrow委托(前三个输出)和保存状态(最后输出)期间statusLabel的输出 enter image description here

2 个答案:

答案 0 :(得分:1)

我找到了解决方案,而不是错误。我使用过的“CustomPickerMenu”类不止一次被调用过。在init(帧)和init(解码器)期间。这就是字符串的值在第一次调用期间最初分配的原因,并且在第二次调用期间变为nil。

我最初通过故事板将委托连接到xib,然后我从一个视图控制器调用xib类,最终将调用xib init(frame)。我编写了代码来加载xib的init(frame)。由于我已经将xib与故事板连接在一起,因此xib也将其称为init(编码器)方法。

所以我做的是,从storyboard中删除了委托,并在其init(frame)中调用了“self.pickerView.delegate”和“self.pickerView.dataSource”,最终init(编码器)方法停止调用。

现在,string的值没有变化。

答案 1 :(得分:0)

执行这些检查,看看您的代码是否遵循相同的规则。 delegate是一个弱变量。

  • 由于委托是可选的,请确保您不要强行打开它。使用?代替!

  • 确保此委托指向的类正在实施协议。

  • 确保在已实施的课程中为delegate变量分配了self

示例游乐场演示将是。

class CustomPickerMenu
{
    var statusLabel = String()

    var pickerArray = [String]()
    weak var delegate:Sample?

    func call() {
        pickerArray = ["One", "Two"]
        print(pickerArray)
    }
    func pick()
    {
        statusLabel = pickerArray[0]
        print(statusLabel)
    }

    @IBAction func saveStatus(_ sender: Any)
    {
        print(statusLabel)
        self.delegate?.doSomething(data: statusLabel)
        print(statusLabel)
    }
}

class Apply: Sample {

    func test() {
        let picker = CustomPickerMenu()
        picker.call()
        picker.pick()
        picker.delegate = self
        picker.saveStatus(self)
    }
    func doSomething(data: String) {
        print(data)
    }
}

let apply = Apply()
apply.test()
相关问题