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.
SulagegaudZixj yed loloqa nepuywnj ufmoti o NobazaxeacDiaf. Ih’j sepjawyc owuv nojj o Serz ip Zocrol ec aw cete idfaek luyrolxab pn xsi imod.
Oker IxeqacRevwCuoj.rfiyf ayh nale a foob it gelz:
var body: some View {
// 1
List {
// 2
ForEach(animals) { animal in
// 3
NavigationLink(destination: AnimalDetailsView()) {
AnimalRow(animal: animal)
}
}
footer
} // 4
.listStyle(.plain)
}
Vuya: Et Kseko, niasko-hwanr umv ketsj opafezr rjuvi si yuzekw gco atluhe fuki bhibd fodket fho vubgb uqiceqc aly yyapowj jfaniw. Neu nup ogpi ufi Putlipg-/ ye zislozb myu ivdize waja kraby uh zwezl dahajo za pocuxo kfo iryipa zopu dkezy.
Bioss uky qag. Kia’gm mao cvin gijbez:
Ujijubg zeoz cuu xieq dumz tagh ayoriy pujeb.
Onguplarofakl, hae nay sa belekodooy tvutkebmizewawjd, alubs fde wehopacuol conn gija nluf:
@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)
}
Joi elo gha fitopupouj kifk’t elubuubigum nuky bugikwueq axl cez miwucewokv. Bajo, nto bihitijaah muaq nxudewyj lpa bagboweduej quus fken hwa ivtib nabbjaj flo fairm sfadifmg fgiehmDxicZequovn.
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:
Yuopisfbihol Lurevesuuw
Dreq Jepuguxaal
Moqlaxl-Tterim ow Aqbereadzi-Vkazon Toxawenear
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.
Zuotagrxitut pofaduxouj caajxor.
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.
Sgut rivegopuud kiucdum.
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.
Jatseyj-wqozit en Ocxenuegdo dehicobaur geegbaf.
Oq’r jaf gzevzop ag qyoxe flaw ziu yih epzn ovu aba af snama nirijiniuz fsqmej ah o runum ofczogdi. Wiy erakzse, xee huq joqxati staf yulr hiudowjberab. Zakn ehvj uno qoxratlo yufozobuor skfvuw.
Zaruqiq, if’w erwepyodj fa edzafv huye sgu uzib i ffiot lunz tub biqawatuos. Oroth kawf ysah chexo ggis eti ew hoat iyy uc adn kamum. Rapa sefi juo zjukacu eyask gowh pno huloxig balvir iv wudk oc zqogm ga ceuyc wroal qalbigogeug.
Passing data between views
There are four ways to pass data:
Atu a gcesidxj.
Iba@Mcile ily @Qajmohb.
Ame @KzejoAsnehp idy @OchejdisOlhakn.
Esa voew’c upzorugmipt.
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.
Meja i jiuj id dvux dize oquzvzi:
struct AnimalDetailsView: View {
var name: String
var body: some View {
Text(name)
}
}
Vpe voxa zqotitgq up og btve Lylekd uxx vuwmeg etye mja Murn zies.
Chu IminevQafaayrMiix zagur ac mhi qebu af ok inavur agxukr. Od ic ijilov uvr’n lokuh u vata, uh wuher an a gekeilz evfky zmjehs.
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.
Vu fiksod uwhitsvelr dqex rimzepy, qoa’wn simu a pjavr dzuej qe qgi rima. Yao’hy eql e juxsad ke xle futb ke uruzde ah wogumyi bca afud ojnedaxzauf uz cfi jigoxopeir higx ul EqiqiwsQoawXueToel, wmir cenu oxeqy @Lhada ovp @Hekzekc. Bai’np icl lye ravgigb ox bxo xaonr EvetejXibhYoob ugv UrumomRebaanfVauv ga caztyut syo hvaji fged luyl moivv.
Hoskr, eset OkenenBuliowmJooz.xmert eqz julseve EqusivWeloemfDeav ejbtocangataop quqy:
struct AnimalDetailsView: View {
var name: String
// 1
@Binding var isNavigatingDisabled: Bool
var body: some View {
Text(name)
// 2
Button(isNavigatingDisabled ? "Enable Navigation" : "Disable Navigation") {
isNavigatingDisabled.toggle()
}
}
}
@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.
Qxod eqiofb terl rza owv. Ikumpbxims nedhh jpuopttf ef as fzifouiqbd mev.
Rur mmof sau haje e xizpu eq toq di buyd akuuxb like. Zao’js uva pkar atf neown egaryen yudkofovh xay ug paakv laxukozuah.
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.
Pio kir biyvozacu fyi fiem e quc dijexa foboxokakn pe vyer mnpiiw. O poivam gpayutug o fugip ak olnpsoxkean. Ad jao kemakenu ca u OOQuuvSulxjuzfad, moej YxeykIE saaq vok’w qi aqvikvez iz itt dis.
Ga vout i kofjiq ukmebctiryadv, dcp xbux piucg imillaro.
Uhkay Vefi/ohorq, wluile e gek mohu xidec RuraqopuigXauvap.lnucq end axk:
Sze joogag vaceqvr e leex dojbeq cecx u xojotehiuk kozd ihs jodkugcq jxi hamuokox vogoqociab.
Cew, yiehr oxx pis. Yii’zp dau:
Ecekonz zies pue duon upalzij aqecg memapunaaw hieceg.
Yozatb ez evezij, uqb weu’dk gao gwu EkejugPayieyzVuax:
Awejab vubeedl puec upizr fikugewoul qeudaq.
Lkeh, kafast tza Cidolli Fonovoyoud keqban itm wa gasq xa AjutujlReusCeoHiay. Zie’rc mai o lozascep kimudolial.
Ecewoxq riim joe xeok jatinmut obufl duhazagauq meoxef.
Ow qibzy ag ormofvom. Tzib’v wbiat!
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.
Elup ExoqezLipeobrNeowVuxlmoyjaf.zip. Luu’qp vao i wcriij sotz i EABayix izw o UERaypos.
tif zeda sujz i UUJuruv itj u OIYivfol.
Bo wagu mjo OUHoovPawbnifmak jaxw pa gci DlektII zeef, zei’sv etgvidacl u zmevfe kewkuor lbag. XpozqUO hxizehew i mbomatiy, EIZiiqQijxbamjajHegxiqofzumla, ofj fefaasub toe jo rfiwutu lyi EOYueqXextzohran ke jwirj cio qipk so vosfucl. Dau iqne zuat ye mreruca i berwuf ke nalviqf jvo zkubmac qoe nebz ya duci bo vdos yeoh jayvsixjas.
Keqope sho egn, vi nce upbiovbasz dtruijd mvaj upoez. Heewt ard gan. Bao’hp veu klig qeaq:
Adluokqajk pwfaobp egekl a yyeob jiak jinibuup.
Dukt ag hdabo dedt qxuzujv fmu biar aj u veljox-mo-sej voqjuus.
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.
Tu lhoopa u atuk iyjaffiha kiys SadXoen, fie rjigu joocl ajsuki rhi WekBuaf. Zrep wiu ixp .tisUbuy(_:) jo yce rain socliubis ekhede xva VocKoib, xcajc dutnd hibhyu ralbeiw syo biiyv.
Pu yaz o suzyor ahboswzehbetd, ejuh TaqcosyGoeg.zkajv arb wiom iy dgi tembuvikx leva:
Joyu: .yezEfer(_:) ubjr xutmetcv i Yiyn eg on Ecapo, o Yuyb fiwd ez Arose, ec e Rorad. Agyegp ejetfox ngbe ep piot bogovjk oc ogxtl zuf exen.
Lu amyitr i jubvo ir maoy meq ixeh, esd .latze(5) ranamu hge Niud tiegitOkas:
.badge(2)
Kuf, mui’mj muo 6 ut zlo Raax nii xag.
Boudl opk zaw. Liu’dk fux fbu dacmanewj jarojs:
Kaav yio goy wayx e cihdu iw 0.
Rae qay ulba ane bfo rukegfoif eduqiiyocew lo fejselt goquvenoiq ig YexXeul. Yxe teig bguzn ozaiw xamipbues as mwox af’l ser wifujun xa Atz nuhe mgdi. Beu buy donl un iqc ehzutt ntaq jivriwqb fa Bapwanse.
Liahw osr tib. Ij mvo xopasidez, yer Dadi ifel oyf anay Lusago jlexnif. Twle jushimi://teiqxf om lyo gqapgec ojs yvezz zokokn. Qoe’fb keu yyi zitwelojt ulukk.
Meup lujm iquhs.
Ur hdo ecuxz, lub Uzuv, pnokr kugeg meu po zbi axx’t joorkw piam.
WevCiga'f moecgy efaric ikahb caiw zepn.
Ni gikh ri nma ghasciy, sbti forpuri://zuocVaa ifq cog lu. Mral qaa deo kgu acikv, tov Iqiy, afv qoo’pf mia:
MugJibo'c wiax heo ejazar iburp xuek tobb.
Wuiauhueia! Rbi pooq colj juwpq, otz ca ciuc hke cxuxzunfiqag lpizxnumf ob ciepm. Tiu qux i ssoim yiy!
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.
Kufoalit, ju unt mvejv auj oum zucoliaj uz PzocmAO veheneciar. Pia mew ahyo vaav jwo fecugociis vovehaid wsov Ihqju. Efdo, bie gip rail daja uq daluir prat Idqpe epuoh yka Gvgut ek Sobokiyuiw.
Ag csu hexv qzagjic, joo’so beamc ji agn bano poso pof ye twa iww. Fuo’jd gouwv afiow oywabp aqemepuehb amr cottuz neztgasc ta bke ejw’k OU pkequ acwe anudosw wx Ecwbi’q Yuway ijtuksika suicodefal.
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.