Skip to content

Instantly share code, notes, and snippets.

@tgnivekucn
Last active December 3, 2021 13:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tgnivekucn/e93bc51a4d651c6ef7b560e9c7644d21 to your computer and use it in GitHub Desktop.
Save tgnivekucn/e93bc51a4d651c6ef7b560e9c7644d21 to your computer and use it in GitHub Desktop.
IOS combine framework sample
import UIKit
import Combine
class ViewModel {
var updateLabel: ((String?) -> Void)?
var textString: String? {
didSet {
updateLabel?(textString)
}
}
}
class ViewController: UIViewController {
@IBOutlet var mTextField: UITextField!
@IBOutlet var mLabel: UILabel!
var sub: AnyCancellable?
var model = ViewModel()
override func viewDidLoad() {
super.viewDidLoad()
// Update UI
model.updateLabel = { val in
self.mLabel.text = val
}
// With FRP
sub = NotificationCenter.default
.publisher(for: UITextField.textDidChangeNotification, object: mTextField)
.map({ ($0.object as! UITextField).text } )
.receive(on: DispatchQueue.main)
.assign(to: \ViewModel.textString, on: model)
// Without FRP
mTextField.addTarget(self, action: #selector(textChanged(_:)), for: .editingChanged)
}
// Without FRP
@objc func textChanged(_ textField: UITextField) {
model.textString = textField.text
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment