BMViewWithViewModel
public protocol BMViewWithViewModel : BMView
A BMViewWithViewModel takes the BMView and UIView a step further by introducing a view model. The view model is an object containing a set of properties reflecting the state of the view. A view model makes it easier to mock a view by passing the state from the outside and therefore test it in any desired state.
Example
struct ProfileViewModel: BMViewModel {
let name: String
let age: Int
var isAdult: Bool {
age > 18
}
var badgeColor: UIColor {
isAdult ? .green : .red
}
}
class ProfileView: BMViewWithViewModel {
let badge = UIView()
let nameLabel = UILabel()
func configure() {
self.addSubview(self.badge)
self.addSubview(self.nameLabel)
}
func style() {
// style the elements
}
func update(oldViewModel: ProfileViewModel?) {
self.badge.backgroundColor = self.viewModel?.badgeColor
self.nameLabel.text = self.viewModel?.name
}
func layout() {
// layout the subviews
}
}
By conformimng to BMViewWithViewModel
in this previous example, we notice we do not explicetely need to specify the viewModel
since it is infered by swift through the update(oldViewModel: VM?)
method.
By altering the view model, different states of the view can be tested in a fast efficient way.
-
The type of the
ViewModel
associated with the view.Declaration
Swift
associatedtype VM : BMViewModel
-
viewModel
Default implementationThe
ViewModel
of the view. Once set,update(oldViewModel: VM?
) is called by leveraging an Objective-C runtime called Associated Types. There is no need to explicitly set this value. By calling update with the properVM
value, the type of theviewModel
is inferred thanks toSwift
.Default Implementation
The ViewModel of the View. Once changed, the
update(oldViewModel: VM?)
will be called. The model variable is automatically created when conforming to the ViewWithModel protocol. Swift is inferring the Type through theoldModel
parameter of theupdate(oldModel: BMViewModel?)
methodDeclaration
Swift
var viewModel: VM? { get set }
-
update()
Extension methodWill throw a fatalError. Use
update(oldMdel:)
instead.Declaration
Swift
func update()