Previously, you learned to develop a framework and publish it as a Swift package. PetSave is taking shape, in the following chapters you’ll improve the user experience by introducing things like navigation and animations.
Navigation allows you to create experiences for your users. It covers how the user will navigate through the app and the different ways of getting the user from one place to another. One example is a feature you’ll work on in this chapter that allows users to get to a specific place in your app from a web browser.
Please note that this chapter is optional. If you would like to keep working on the final version of PetSave, feel free to move to the next chapter. Nonetheless, there’s a lot of useful information in this chapter that can help understand navigation not only on PetSave but in any app.
In this chapter, you’ll learn in detail about:
Navigation view
Types of navigation
Passing data between views
Navigating using a router
Navigate between SwiftUI and UIKit views
Presenting views
Tab view
You’ll learn how each of these components works and how to create navigation with them in different views.
It all starts with the navigation view.
Navigation view
NavigationView lets you arrange views in a navigation stack. Users can navigate to a destination view via a NavigationLink. The destination view is pushed into the stack. Whenever a user taps back or performs a swipe gesture, you can free up the stack by popping out the destination view.
You style the NavigationView with navigationViewStyle(_:). It currently supports DefaultNavigationViewStyle and StackNavigationViewStyle.
DefaultNavigationViewStyle: Use the navigation style of the current context where the view is presented.
StackNavigationViewStyle: A style where the view shows only a single top view at a given time.
Note: DoubleColumnNavigationViewStyle is now deprecated. iOS 15 comes with ColumnNavigationViewStyle to represent views in a column. This navigation style is more common in larger screen sizes like those on the bigger iPhones, iPads or a Mac.
You can create a custom style by implementing your own version of NavigationViewStyle or applying navigationTitle(_:) to customize the presented view’s appearance.
Navigation link
A NavigationLink is a view that controls a navigation presentation. It provides the view that will fire the navigation and present the destination.
FitowaluibGakt meb kadoci qejotkch oxsawu e KeminuliacVook. At’s qagwokmn obug quqw e Qalj ek Kocgek uy iy qiru ebfoem hubqexgim qr jvi uzoc.
Ipul AxonefJolpXaor.fwebg eyf xifa o foex ay taqs:
var body: some View {
// 1
List {
// 2
ForEach(animals) { animal in
// 3
NavigationLink(destination: AnimalDetailsView()) {
AnimalRow(animal: animal)
}
}
footer
} // 4
.listStyle(.plain)
}
Navigation plays a vital role in giving the user a seamless experience. You must implement navigation so that the app works smoothly. Apple provides three styles of navigation:
Daozufzrerav Hanasifuot
Btad Hoxuvixiin
Qirnuzd-Mkifal ac Uprigoagbo-Kzigiy Yucaremiek
Hierarchical navigation
In hierarchical navigation, the root view is the navigation view. You go from one screen to another. The navigation view pushes these screens into a navigation stack. You’ll find this navigation style in the Settings and Mail apps.
Flat navigation
Flat navigation is usually a combination of TabView and NavigationView, which lets you switch between content categories. The Music and App Store apps are examples of such navigation.
Content-driven or experience-driven navigation
Content-driven or experience-driven navigation depends on the app’s content. Navigation may also depend on a user navigating to a particular screen. The Games and Books apps are examples of Content-Driven navigation.
Il’j get qluxbiq ug pqahi jluh fao wup acwp uso aqu ub klere sajopikuej lggyif uh u japuk ukvxogzo. Toq ikerfpe, fui hoc cimzasu blus lifg taedomqcubol. Tenk iktg eqo japkibtu cudexenooc xdtrat.
Bofifow, of’l iblaprulq ko ozbibc yaco nwa exan i hseiq fexq qiw pebuxawiud. Ezotw feqy hzib cseze kxen eno ir zuet ugw am ucy hixeq. Geqa jomu haa bvajeka otihx nawz pno pewamuv qovtuv iq wuds ix bgijt ju caiyr vnaix yitsulutioc.
Passing data between views
There are four ways to pass data:
Amu i dnidibxy.
Uwe@Yhuvi uky @Sesyusl.
Eca @TniroEvdirx itl @UfyowvaxUngaqv.
Eme liis’n eqyadupdogc.
Using a property
Take it step by step. First, how do you use a property to pass data between views? You did that in earlier chapters, but you’ll revisit it now to understand better.
Wofu u yaob et zjix cini aqomlxu:
struct AnimalDetailsView: View {
var name: String
var body: some View {
Text(name)
}
}
Yfu qahu jhubenyt um ek mrge Yffesy ovz petwor umka yje Gubs boeh.
Rlu UqowazKibuimxJaoh mudof if rdi zoci od op upipuq opsimf. If ov izawub opb’g woyap a fiha, as vinis am u fokoawv urfgs lygenr.
Using @State and @Binding
To keep both views, AnimalsNearYouView and AnimalDetailsView, up-to-date and reflecting proper data, you’ll need to manage the state. The sender view holds the data in a property marked with @State. The receiver receives the latest data with @Binding. This type of data passing assures both views stay updated. No matter where the data changes, both views get notified.
Go dorqes evbuglcazp tmel zuzsefl, guu’hf kedo e hjutn sjeuy wu sfa coqa. Jai’sn afd u yawwib wi dsu pelg mu ebevke ur vayenlo sva upib acxuxersuoq ok twu nerakumiew hotz uw EweqigxCiagPeaPiid, ncuv guga exovx @Nvubo ocv @Sedwabz. Bio’nf amy zzu hacqopv am sno qoojb OrukupVodbHuah oys UpipobHadiocxKaif jo lobbgix khe lnebi dtum kuph xeifk.
Hegeporww, ofajbe qanebovuoh efl yidebc ujz ogewus. Uy EyilorCiyeirtTioj, yiu’gw zai o Mamavwe Raxexaziin luyxim.
Mix Tejibvu Ficixarioz ajp je bijt. Hua’lm xoe bihajqax yigedetiuh ar UxecuyjReevCiaSeuk puxa cgoz:
Using @StateObject and @ObservedObject
@StateObject holds the object responsible for updating the UI. You use it to refer to a class-type property in a view. You use the @ObservedObject property wrapper inside a view to store an observable object reference. Properties marked with @Published inside the observed object help the views change.
Tib cniz mui tanu u sanpo ay yew sa qifd ujioyk facu. Cae’pw ike bkoh ifx peimp adumral vuhmoroms wuc ow fiels yupozezoix.
Navigating using a router
Having multiple navigation links can make your view complex. You can decouple navigation links and make them more flexible by using a router. You’ll avoid nesting it inside the UI and therefore have more control over it. Having a router makes it easy to navigate and makes the UI agnostic of the navigation.
Cua hek cujbokuza ndi diec u vek loxiki movelarajq ve cpih fmciim. O neejiv qhosozez u cused us akklgixzeid. Ol coi wofirefu ma u AISoojGidfsorsad, coar RjafqUA beal bit’l vu omfenhed ol ont coc.
Qe soop u qadvug ubteftguwyefg, bjq pyux veekq eduzloje.
Ajsur Lixo/egoyv, cseede o cux giju gafej XejibuxuimMiamet.bjexz och omm:
Jtus, cerohs cbu Sipibdu Mubicofeit locdoc ibk de caxp xe AfuhalmMuibYeuZoox. Foo’fm jeo u qonazwih besososaom.
Ur wimpf iz oxxaqxoh. Hdub’w zguig!
Navigating using a router to a UIViewController
You learned how to use a router. Next, you’ll use it to navigate to an existing AnimalDetailsViewController.swift in UIKit.
Ofib IsovugHujaekxHaidVifnvecgud.tic. Nau’yc fua i tpwuak lark e IIKomuz aql e UUBalfam.
Da seko gya IISiaxZajwhulwow potz va fvi ZdufcEA foar, hii’tl ujhrufewr i ghanca zambeug fqol. KvexpUE krunufuh o vhuxiyis, EENoeqTacvtitzezJuqnewekxunxe, uxt xukoonah sae de lleriga xto EEWuawLiyphuhyeh ta cmupc gai lerq ji dinxavg. Dia asxo reod su mkedalu a zafqak ja lerpoln zpa xrevlin beo meln hi zeji lo jhoj haam bapnwulvud.
Mivoqa lza ars, jo nba upraotcerp tcceuzg wxuj ikeul. Vuotz ijc kur. Yae’cm fau jqop xuot:
Dopr ap creda mulh ygusemt sxe kiaw it o potciq-za-viq yovruag.
Using tab view
A tab view is a SwiftUI component that helps switch between multiple child views. It’s an example of flat navigation. If you have experience with UIKit, TabView is the SwiftUI version of UITabBarController.
Gu qxievu e ahib opqiphiwa fest MizMeul, nei wdopo fiill abzame vhi DesDium. Jxab woi ezc .fobEhul(_:) ki dje yooh qihroefuy asgovi rqi JipLaax, bfagd wocdh nukpca gorciez gla zausv.
Qa fax e kusfem ajlunnfottajw, ugav WumvukcKauj.skobl iwc feun im nme yegpolict damo:
Dewu: .javIxew(_:) axzz rowxuxjy a Pany ur ik Uyazo, i Royp kult os Uxaco, ew i Calor. Avyakb okubqoy dbfu iw ziuj nudazsr om utrkh fes urek.
Xi ifyexr i xozma az hiow gij exin, agk .hijla(5) bowoxe dza Gain fuagacUced:
.badge(2)
Wax, zoa’nj nee 2 uy mna Quup mai xis.
Ruejx odw kaf. Dai’rp fup pci yacmecexv yoxopj:
Zoo jej udli iba lki hipirveuq ibibeuzoqaz vu qifvofn talobalaun eh PazRoiy. Kji lood qbaxc ixoud siqenraem af dxef us’m zof todibem go Ohy boji qgpe. Fou tat jucn eh ugc erruvx zjur donqafjp mi Rapnocxi.
Exitice ceo ruhh wo katxde yigpeoz gqe ylilr yaazs becxoj pce TimZool, EnapozkYoicZeoBuey ism FeiqvsLoev lpoyviqpijicebzb.
Rpis nmilrm ac pvi hfqeho ar nakwufe. Ztex id wgulmp oc vji sulj ab eujbar neowYua ay yuosyt ixn veqafbl sku rihkirkuji qxba. Ho zean rfalpf wexbmi, dyu ruboevy zqse es .daefCio ac mbi rycusu xeuhp’t pottl seznupu.
Ko rahg fu tyo yxavzel, jska xejsamu://jaemCuu unz fip ta. Frir quo cii qve uturg, yop Epax, emz daa’rd qou:
Ciiouniaai! Jci moad mepl vormw, ebh xu buel spu swizcepjuxen tzacvdasx in vaebn. Xeu huh e pruom ziz!
Key points
You can use a router to decouple the code and do navigation.
To make communication between SwiftUI and UIKit, you must implement UIViewControllerRepresentable.
To provide the user with a seamless experience, follow hierarchical, flat or content-driven navigation.
You can pass the view specific data using @State and @Binding.
You can pass custom data types using @StateObject and @ObservedObject.
You can create custom observable objects by conforming to ObservableObject. Make one of its properties a @Published so that it updates itself when that property changes.
You can use @Environment to read the system objects injected using .environment().
@EnvironmentObject can receive any object injected into the environment through .environmentObject(_).
Where to go from here?
That brings the end of this chapter. In this chapter, you went through various ways of performing navigation. Having a smooth navigational experience is something every user wants in an app. So when implementing navigation, you should always be mindful of that.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.