如何使用swift监听变量中的值的变化?

时间:2016-07-02 06:11:14

标签: ios swift user-interface variables return-value

我有一个字符串类型变量,其值通过PickerView更新,当该值更新时,它会更新按钮的标题,如下所示:

@IBOutlet weak var selectedCountry: UIButton!

 var pickedCountry: String?

func checkForPickedCountry() {
        if self.pickedCountry != nil {
            selectedCountry.setTitle("\(pickedCountry!)", forState: .Normal);
        } else {
            selectedCountry.setTitle("Tap here pick a country", forState: .Normal);
        }

更新

就像我提到的那样,我正在使用pickerView来更新pickedCountry的值,当从pickerView中选择一个国家/地区时,它会显示另一个标题为selectedFlag的按钮,然后再拍摄另一个pickerView选择国家标志。现在我想听第一个pickedCountry var进行更改的原因是我可以将selectedFlag按钮的标题更改为默认值。

所以这是我的最终代码:

@IBOutlet weak var selectedCountry: UIButton!
@IBOutlet weak var selectedFlag: UIButton!

 var pickedCountry: String?
 var pickedFlag: String?

func checkForPickedCountry() {
        if self.pickedCountry != nil {
            selectedCountry.setTitle("\(pickedCountry!)", forState: .Normal);
            selectedFlag.hidden = false
        } else {
            selectedCountry.setTitle("Tap here pick a country", forState: .Normal);
            selectedFlag.hidden = true
        }


       if self.pickedFlag != nil {
           selectedFlag.setTitle("\(pickedCountry!)", forState: .Normal);
       } else {
           selectedFlag.setTitle("Tap here to pick a flag", forState: .Normal)
       }

现在如何将selectedFlag的标题设置为“当PickedCountry的值发生变化时,点击此处选择标记?”

3 个答案:

答案 0 :(得分:2)

您可以在变量中实现willSet,以便在变量发生变化时每次调用函数。您也可以修改您的函数以获得这样的新值:

var pickedCountry: String? {
    willSet(newValue) {
      guard let oldValue = str, new = newValue else { return }
      if oldValue != new { //....Your value is changed }
    }
}

func checkForPickedCountry(updatedValue: String) {...}

答案 1 :(得分:1)

你可以使用简单的逻辑作为Below ::

  

设置一个Int变量var flag : Int = 0现在整个程序标志有0个值。

当您点击按钮时,再次通过self.flag = 1将其值更改为1.再次点击第二个时,请将其设为0,方法是self.flag = 0.

  

通过获取该标志变量的值,您将听取该事件。

你可以通过提供值2,3,4 ...来标记变量

,从而为两个以上做同样的事情

答案 2 :(得分:1)

您可以使用键值观察器监视它。

在应该查找更改的类中,执行以下操作:

添加观察者

func addObservers() {
    let observerKeyLocation = "pickedConuntry"
    classThatMonitors.addObserver(self, forKeyPath: observerKeyLocation, options: .New, context: nil)
}

然后,重写observerValueForKeyPath函数:

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    if keyPath == observerKeyLocation {
        if self.pickedCountry != nil {
            selectedCountry.setTitle("\(pickedCountry!)", forState: .Normal);
        } else {
            selectedCountry.setTitle("Tap here pick a country", forState: .Normal);
        }
    }
}

现在,每当更改该值时,您的观察者将立即更新,并可以调用您放置在其中的代码。

请记住,如果你去除被观察的类,你还必须移除观察者以避免崩溃。