2017-06-28 104 views
2

我試圖使用志願與志願

我的目標是創建一個簡單的模型MVVM MVVM簡單就是當的UITextField文本的變化,自動改變的UILabel文本。 但由於某些原因,observeValue功能不叫

import UIKit 
class ViewController: UIViewController, UITextFieldDelegate { 

    var viewModel : TestViewModel? 
    @IBOutlet weak var LBLABEL: UILabel! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     viewModel = TestViewModel() 

     addObserver(self, forKeyPath: #keyPath(viewModel.infoText), options: [.old, .new], context: nil) 

     // Do any additional setup after loading the view, typically from a nib. 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { 
     viewModel?.infoText = textField.text 
     return true 
    } 


    // MARK: - Key-Value Observing 
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { 
     if keyPath == "info" { 
      // Update Time Label 
      LBLABEL.text = viewModel?.infoText 
     } 
    } 

} 


class TestViewModel : NSObject{ 
    var model : TestModel 

    var infoText:String? { 
     didSet{ 
      model.info = self.infoText 

     } 
    } 

    override init() { 
     model = TestModel() 
    } 
} 


class TestModel { 
    var info:String? 
} 

我已經試圖改變觀察者的聲明,甚至視圖模型獲取並設置和從來沒有成功

+0

您是否在代碼中的某處添加了'textField.delegate = self'? –

+0

@Ahmad F - 是的。在故事板中。我在'shouldChangeCharactersIn'上放了一些斷點,代碼停在那裏。模型和視圖模型中字符串的值被正確更改 – Pedro

回答

1

UPDATE

據蘋果docs,創建關鍵路徑的觀察者將在Swift 4中簡單得多。

class MyObserver: NSObject { 
    @objc var objectToObserve: MyObjectToObserve 
    var observation: NSKeyValueObservation? 

    init(object: MyObjectToObserve) { 
     objectToObserve = object 
     super.init() 

     observation = observe(\.objectToObserve.myDate) { object, change in 
      print("Observed a change to \(object.objectToObserve).myDate, updated to: \(object.objectToObserve.myDate)") 
     } 
    } 
} 

let observed = MyObjectToObserve() 
let observer = MyObserver(object: observed) 

observed.updateDate() 

您需要將dynamic添加到要觀察的NSObject子類的屬性中。你的情況:

@objc dynamic var infoText:String? { 
    didSet{ 
     model.info = self.infoText    
    } 
} 

順便說一句,我不知道爲什麼你要你文本框:shouldChangeCharactersIn,因爲它得到之前更新文本字段值。此外,keyPath == "info"永遠不會是真的。它不應該是別的東西。例如,keyPath == "viewModel.infoText"

+0

感謝@objc動態確實解決了:D – Pedro