class SomeViewController: UIViewController {
private let someTextView = UITextView()
private let someTextField = UITextField()
private let viewModel = ViewModel()
override func viewDidLoad() {
super.viewDidLoad()
bind()
}
private func bind() {
someTextView.textPublisher
.receive(on: RunLoop.main)
.assign(to: &viewModel.$textViewInput)
someTextField.textPublisher
.receive(on: RunLoop.main)
.assign(to: &viewModel.$textFieldInput)
}
}
class ViewModel {
@Published var textViewInput = ""
@Published var textFieldInput = ""
}
import Combine
extension UITextField {
var textPublisher: AnyPublisher<String, Never> {
NotificationCenter.default.publisher(
for: UITextField.textDidChangeNotification,
object: self
)
.compactMap { $0.object as? UITextField }
.map { $0.text ?? "" }
.eraseToAnyPublisher()
}
}
extension UITextView {
var textPublisher: AnyPublisher<String, Never> {
NotificationCenter.default.publisher(
for: UITextView.textDidChangeNotification, object: self
)
.compactMap{ $0.object as? UITextView}
.map{ $0.text ?? "" }
.eraseToAnyPublisher()
}
}