我試圖使用志願與志願
我的目標是創建一個簡單的模型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?
}
我已經試圖改變觀察者的聲明,甚至視圖模型獲取並設置和從來沒有成功
您是否在代碼中的某處添加了'textField.delegate = self'? –
@Ahmad F - 是的。在故事板中。我在'shouldChangeCharactersIn'上放了一些斷點,代碼停在那裏。模型和視圖模型中字符串的值被正確更改 – Pedro