Search code examples
swiftuitvosswiftui-navigationlink

Navigation in SwiftUI button for tvOS disables animation


I'm working on creating a tvOS app in SwiftUI for the first time. I'm pretty new at this.

I have a row of buttons, which works properly. Whenever I change focus the item in focus increases in size.

var body: some View {
    NavigationView {
                ScrollView(.horizontal) {
                    LazyHStack(spacing: 50) {
                        ForEach(sections[0].items) { item in
                            Button {} label: {
                                Image(systemName: "photo")
                                    .resizable()
                                    .frame(width: 300, height: 170)
                                Text(item.title)
                            }
                            .buttonStyle(.borderless)
                            
                        }
                    }
                }
                .scrollClipDisabled()
                .buttonStyle(.borderless)
            }

}

However, If I try to add a navigation link like this:

NavigationLink(destination: VideoDetailView(mediaItem: item)) {
                                        Button...
                                    }

the animation on focus is lost.

What am I doing wrong? How can I maintain the focus animation of the Button and have it take me to a new screen?


Solution

  • A NavigationLink is a type of button, you do not need to use it to wrap a Button. The modifier .buttonStyle can be applied to a NavigationLink too.

    Also, NavigationView is deprecated, consider using NavigationStack instead.

    NavigationStack {
        ScrollView(.horizontal) {
            LazyHStack(spacing: 50) {
                ForEach(sections[0].items) { item in
                    NavigationLink {
                        VideoDetailView(mediaItem: item)
                    } label: {
                        Image(systemName: "photo")
                            .resizable()
                            .frame(width: 300, height: 170)
                        Text(item.title)
                    }
                    .buttonStyle(.borderless)
                }
            }
        }
        .scrollClipDisabled()
    }