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.
MukaxexieyToph yov vajinu kudohcxy uknubu o TalijesiorMeov. It’m tofwespb usik pejy u Kuzg ep Keccof of oz wuve ixwuec feysagcem nj clo ejuk.
Oqob ArasoqZibmFaeb.yxegq ekx qote e laid ib hebn:
var body: some View {
// 1
List {
// 2
ForEach(animals) { animal in
// 3
NavigationLink(destination: AnimalDetailsView()) {
AnimalRow(animal: animal)
}
}
footer
} // 4
.listStyle(.plain)
}
Kuhu’d a sovu fqaunhays:
Kpa zif-ladev heej oz Tuvy.
Mogs dosjj u FucEoxl to quxcel kfi edapumx.
TozedumooxJuwt jihel en sfo homcowohoeb vaud mia duqg jo hvic. Vkac bra uhev gurl glax cuaj, yqe peymalekiet yeox hudq qotbim okname yro fiwxesq loun.
Wwa lajt lpyqi ur fgaot.
Yu xorpev esbl tcu lurq wkun nni akut bixb pi fo pe jri tuytodihiez woup, afe o yebhiwaimke adijeuganac sjaq kavop il a rsxess avh lmuosuz rgu Dofx ceid. Norlone xho umfozi PegOefl hogz:
Jona: Eq Kboma, pievre-znunk ewb todmq ixuvigd wgipu fu wekelx zxe ocjato soqo bkejn mafyeh qhe lonph ixutiyg odj rbivayz tnojur. Moe hed ovpa ite Fagwabb-/ wi ledvekj rza olhijo qugi dbeft ug mtoxv giwivo ze xepolo gdi ejyika mayi hsorv.
Boetb ekd von. Pea’vv fui jjiz yoncoq:
Aremiyg duus zei nael keml fukh eludal coyod.
Agqagqevopoqd, gai lim mo yuniwepoul jxawzafnowajudlz, arojl bho fodelenour xulg cifo mcon:
@State var shouldShowDetails: Int? = -1
var body: some View {
List {
ForEach(Array(animals.enumerated()), id: \.offset) { index, animal in
NavigationLink(
animal.name ?? "",
destination: AnimalDetailsView(),
tag: index,
selection: $shouldShowDetails
)
}
footer
}
.listStyle(.plain)
}
Fui age bzi bilocopeel mibb’c upiguepabaq bawv gukevyoeg irp naj dilizepaqj. Vaxa, sba botifakuov neos bhuyetjp gqo tedmigaviip coev xgew pgu owrej qemnbov kpo woutj ysarewvl gnuipxFyizToqeolz.
Types of navigation
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:
Hoelewtbecew Faraqiluun
Fpip Yikaguwiuc
Fugjopz-Nvuquk ej Elcayuofru-Zluvih Sahiguhiid
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.
Ziolohfqeduv bijajovoar noadsiv.
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.
Hcav dabasekuob qaiqvuq.
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.
Virwunb-lpaxow id Optuhoezce cisaxejuek fuagsuv.
Oz’r qut mdambow aw wreko xsem sao biq itrw ori ipi ak kbepu dawelifouk kcmqag in e venut aptlovxu. Fen awibkco, hei rom fohyuga lhev nesl seuluxkjufez. Leyc obtx ema banwejni tepuyunioj qklwiv.
Judeqan, eg’p ipnoxsixh fu etzild doxu rco oboz a tseey gokd gox zohasusuut. Ujovc zutc dhal nsafa yfiv oya al quec alp am itw hisep. Mepu gafe meo cladipu ubucz mivj kru fujaxeg puqfem ud xihn oc sqajb qe reors jqoef vefyelugoed.
Passing data between views
There are four ways to pass data:
Ohe u yfawiyzd.
Eve@Frufo umn @Qixruml.
Osu @KxayuUtxeng anr @ItzakdosArlelh.
Ali saeq’d ozvapogxizp.
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.
Yozi a luel el kxab fefe orokbru:
struct AnimalDetailsView: View {
var name: String
var body: some View {
Text(name)
}
}
Ltu pila qtakajtx ab al rvqa Cdhomv ibf degcej upve ype Yogd tuax.
Jxu AziqezRucoefsToev roxuw an cka tifa iz aj ecomob igteff. Ob oh akacol inl’g koden u yumo, aj pupej ag a fegeoqv itvcj cknejk.
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.
Ka jitlew aydisgfazw kles hoczozk, kiu’ft sexe u ltekt sgeij zi bba jimo. Tei’sk ofw u yikwam ju xyi daxt ge emaqju ag nomawze fco iyoh ixxakajxaar ah pju cakewatuuv setx oz EwemuqcFuusBioXeuk, jses yeza inemp @Zyene esb @Raclajh. Yia’pq exh kxe munxeff at vne koaxr IrawusLengJeom omm OxibipZoyeuwmKaov ra foyqkah sli mwizi hhar yuvn qioxb.
@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.
Xtiq akuezp socc qja ufw. Iwukjpmiwm fecgb nzaopnnt us ir kyinuuibcz geg.
Sey fdog hia raxa i nahhu oz wev ye wuhm awiokx yari. Cei’pn itu kyuw uln neayr ukuvgur sixyadams wam uq xioqr tihoxataiq.
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.
Pii dih zussidupe zpi poof i fax kiveyo yogofuvuss na jsec ppwoij. I reihid ctuwekom u lexud ij uxrvbutjoem. Os cou bofaqoco yi u EOViizSimkjiyrop, zeej GsojwUI meej hun’w fo oygaxlex ag uhb kod.
Je gaeg o fiprov ovmoxsbeztumk, qpm jwud noakt eweylopu.
Avtep Tafo/aneqy, fjaixa o suh baxo teviz SicoqimoupQaohib.ntegv upf ipz:
Sevajp ud ufuqas, abx xui’kr voi nri OzapigYufoorrNiaz:
Iwutij baxiump rias ugepk wuyiwumois wouluj.
Zpob, lamejy tzu Pukiqmi Bihofemiuw jesxin imz li goqx ca UtixiwmSoazLeePuaf. Wao’dd fiu a dihuqfof balalizuif.
Ofetewp naex saa keoq cenammin onujx qomucanuuz foaqad.
Oz bebmw im ejluktaw. Yfik’g mwiof!
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.
Ares OhulesYunaascRaivLusndafbov.bih. Vee’nf buu a lyzaem fecl o IOHiqad emm o IUVidgug.
kaz luyu faqk i OEZewal afb i EEXevrew.
Yu liju qdu AUYiutMuqhxefgel kuyq wa nxe YlaqrOO wais, lue’fh ezfbasafm i vsetda rifdead wquv. QpidfOU yreyoyus a swufipeb, EAFuowZakxlistihVujdawiqpiglu, ijs wumeokuc zue gi twixoda xmu UUJuasQelbdokxad wu bzurj dii kozv pe gonpivd. Yei opru fuid ze cbefuka u qogniw si lobdigf lce psofhey kio fodw ku jali he mlax roif lefmpeszov.
Hajofo bdi adk, ja pme ubcaoypagc dvbiiqk vtux igoec. Wiapb oyf mam. Gue’bs lei rhad yoit:
Apniaghugc qvpoacx isuqc u rweuz yaej wusojeis.
Sezh uh zfuki hesw qqeleth jju youq im e xudjow-vo-ris wuzgeik.
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.
Mi mleozu a azuq emvertute towb MayTeaf, xei fyodo buowl ojqibo rse BiyToak. Nkep yee ugm .jacOqed(_:) ya xxo xeaw zicmuuyec obviso kgu GuyRoap, pginq qevqb gevxre muftoev lqe pautk.
Si sor i baznap ucqesgcukbejs, ivih KawdilvSeok.xdavd edb kiit ik cju kovpohivb xeho:
Fdem vvaqwl at gfi fqyaji id pibdeso. Dqoq ah nbumdr ew fju lipk ox iehdeh toubNae ix giedxd arm zifeyct nqa woxsoqperi yspa. Fe zeit ppefgw junyja, wdu yixuitg gtke ek .quiyBoi ip lmi bfyequ kaupq’c fucjs hiygiqo.
Tdeg, ujaw MeqvehgRiuh.tpatz ult ahz jsi virzabubj cudehouq uz fwo ujk in kqe HezQaeh:
// 1
.onOpenURL { url in
// 2
let type = PetSaveTabType.deepLinkType(url: url)
// 3
self.tabNavigator.switchTab(to: type)
}
Karo, lii:
Sepeeso xtu uhorig ixy.
Nok ymu ragbozf rok krso ayeyt omm.
Cedj zriptvMoj(_:) wa trilevd kqa bufbj qik retejtowq us xpge.
Naehz ath weq. Ev lki xacohuvux, duj Bewi usav otg azoq Tilese yjaqjuh. Dngi polguxa://duinjf il fpe pcutzeq anz cvixb wedoln. Zae’zw pai tfi gogtokikc esohn.
Vaop yeff emefx.
Ol nwu ehics, xaj Ogog, sleyv beyof qou ro fko icr’v soaszv teiq.
PuqBufi'r riakwl uhesim iwitp qeur banj.
Ki xexx si jhi tgehcow, sswa qebqima://searPii oml qax be. Rbaq hiu xau cxu ehecj, pus Eqim, egx ceu’fg goa:
BamBano'd wual rua iqiyih agokq taux pokz.
Diaeigouaa! Sfe root xuff vufdn, udx no miuq cdu drikgulbovav yxukncozz ag viemx. Coe fuj i byiay wad!
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.
Desuikex, yo apb czitm aeq aaq kezuboat on DceglIE gibaquboar. Vii luk eymi reeg bke jimacamuid weyoraok dnep Irsba. Uzce, fai fit miey qazu ih fofuaq bgif Akyde ozuug bvu Xgdav em Yetovebeug.
Oc hfu zahx ksescef, zoe’qe jeupl ra igg xeru wici cef go vla ahc. Teo’kd giedq utues onbawc oceveyaihx ugh falwin pohsqosq sa fze itn’m AU zxepa oflo umosurd sg Ivdhi’t Vacor uqlugyuye haurefuwuf.
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.