Last active
December 3, 2021 13:23
-
-
Save tgnivekucn/e93bc51a4d651c6ef7b560e9c7644d21 to your computer and use it in GitHub Desktop.
IOS combine framework sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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