@Published属性与绑定
注意:Combine可以在SwiftUI和UIKit下工作,本例中在Playground中使用的是UIKit
示例一: 将演示在ViewModel使用@Published
属性并将它绑定到视图控件
import Foundation
import UIKit
import Combine
final class FormViewModel {
@Published var isSubmitAllowed: Bool = true
}
final class FormViewController: UIViewController {
var viewModel = FormViewModel()
let submitButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
// subscribe to a @Published property using the $ wrapped accessor
viewModel.$isSubmitAllowed
.receive(on: DispatchQueue.main)
.print()
.assign(to: \.isEnabled, on: submitButton)
}
}
print("Demonstrating @Published")
let formViewController = FormViewController(nibName: nil, bundle: nil)
print("Button enabled is \(formViewController.submitButton.isEnabled)")
formViewController.viewModel.isSubmitAllowed = false
print("Button enabled is \(formViewController.submitButton.isEnabled)")
输出:
Demonstrating @Published
Button enabled is true
Button enabled is true
示例二: 将演示使用ObservableObject
,生成多个@Published
并订阅其值的变化
print("Demonstrating ObservableObject")
class ObservableFormViewModel: ObservableObject {
@Published var isSubmitAllowed: Bool = true
@Published var username: String = ""
@Published var password: String = ""
var somethingElse: Int = 10
}
var form = ObservableFormViewModel()
let formSubscription = form.objectWillChange.sink { _ in
print("Form changed: \(form.isSubmitAllowed) \"\(form.username)\" \"\(form.password)\"")
}
form.isSubmitAllowed = false
form.username = "Florent"
form.password = "12345"
form.somethingElse = 0
注意:objectWillChange
是值即将改变的消息,somethingElse
属性没有设置@Published其不会有输出
输出:
Demonstrating ObservableObject
Form changed: true "" ""
Form changed: false "" ""
Form changed: false "Florent" ""