Как получить два последних элемента из стека объекта NavigationPath()IOS

Программируем под IOS
Ответить
Anonymous
 Как получить два последних элемента из стека объекта NavigationPath()

Сообщение Anonymous »


I am facing a challenge in SwiftUI and would appreciate some guidance. In my code, I'm working with a NavigationPath() object and need to obtain the last two items from the stack. Specifically, this operation should occur within a view named SomeView, which is deep in the navigation stack.

Inside the action closure of a Button within SomeView, I want to assign the last two items of the navigationControl.path to a let constant if they exist.

I've scoured various sources for a solution, but unfortunately, I haven't found one that fits my requirements. It is crucial that the last two items are obtained from the navigationControl variable retrieved from the environment. While I am aware that these items can be obtained by injecting them into SomeView during its instantiation at the parent view, this approach is not acceptable in my case.

To provide a comprehensive overview of the project, I've attached relevant code snippets from other files as well.

// SomeView.swift import SwiftUI struct SomeView: View { @Environment(NavigationControl.self) private var navigationControl: NavigationControl var body: some View { Button("Tap to get the last two items in NavigationStack") { // Not sure what to write here. // It must be something like the following options just to illustrate what is desired: // let lastItem = navigationControl.path.last() // let lastItem = navigationControl.path[navigationControl.path.count] // However, neither of them are defined. // Note that only the last item assignemnt is shown here. However, it is desired to get the last two items from path. } } } #Preview { NavigationStack { SomeView() .environment(NavigationControl()) } } // NavigationControl.swift import SwiftUI @Observable class NavigationControl { var path = NavigationPath() } // ContentView.swift import SwiftUI struct ContentView: View { @Environment(NavigationControl.self) private var navigationControl: NavigationControl var body: some View { @Bindable var navigationControl = navigationControl NavigationStack(path: $navigationControl.path) { Button("Navigate") { for i in 1..

Источник: https://stackoverflow.com/questions/781 ... ath-object
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «IOS»