Show controller state with knStateView
Have you ever add empty state to your app? How do you show loading or error state when call API?
There are some libs somewhere in Github, you can search yourself to find the best one for you.
Today, I show you my approach, knStateView
. You can download my demo at knStateView
General idea
- Make view with
iconImageView
,titleLabel
, andsubtitleLabel
. - Change content by state
- Set custom content by override the state in
contentLibrary
- Set custom state view by override the state in
customViewsLibrary
.
Support states
enum knState: String {
case success
case noInternet, error, empty, loading
}
knStateView
You can check the content of knStateView in the project. I will explain some major things here
customViewsLibrary
customViewsLibrary is a dictionary [knState: UIView]
to contain custom UIs for every states.
If you want to customize the error
state by your own UI, set it here
stateView.setCustomView(your_own_UI, for: .error)
Default error state
Custom error state
contentLibrary
contentLibrary is a dictionary knState.noInternet: (String, String, String)
to get icon, title, subtitle for every state. You can override state you want.
setState
private func setState(_ value: knState) {
currentView?.removeFromSuperview()
// (1)
if let view = customViewsLibrary[value] {
currentView = view
addSubviews(views: view)
view.center(toView: self)
return
}
// (2)
if let data = contentLibrary[value] {
setData(data)
return
}
// (3)
if value == .success {
removeFromSuperview()
}
}
(1)
If custom view for new state exists, we bring that view to the UI.
(2)
contentLibrary
contains our default content for 4 states. We get data from contentLibrary
to display to default UI.
If you already override a state in contentLibrary
, it gets your new content to show.
If the icon is a URL, we download the icon automatically.
(3)
If your app is in success state, simply remove current state view.
How to show knStateView
There are 2 ways to show it
- Add manually to your root view and set auto layout for it.
- Add to a certain view, and
knStateView
fill the whole space of your view.
Notes
- Your custom view must have size (or intrinsic content size).
- You can remove
iconImageView
ortitleLabel
orsubtitleLabel
by set it empty in contentLibrary.
For instance: removesubtitleLabel
stateView.setContent(image: "loading_2",
title: "New loading view",
subtitle: "",
for: .loading)
- You can add a retry callback into this. I don't do that to keep it simple.
Conclusion
This approach is flexible for me to use default UI or specific UI for some screens.
What do you do with state view? Share me in comment.
Enjoy coding.