Home > Blockchain >  Trouble With Constraints for a Navigation Link
Trouble With Constraints for a Navigation Link

Time:01-16

Here is my code:

import SwiftUI

struct ContentView: View {
    
    var link: some View {
        NavigationLink(destination: OtherView()) {
            Text("NLTitle")
        }
            .foregroundColor(.blue)
    }
    
    var body: some View {
        NavigationView {
            List {
                ZStack {
                    HStack {
                        Text("1")
                        
                        Spacer()
                    }.padding([.leading, .trailing], 20)
                                            
                    HStack {
                        Spacer()
                        
                        Text("2")
                            .multilineTextAlignment(.center)
                            .frame(
                                alignment: .center
                            )
                        
                        Spacer()
                    }
                    .padding([.leading, .trailing], 20)
                    
                    HStack {
                        Spacer()
                        
                        link
                    }.padding([.leading, .trailing], 20)
                }
            }
        }
    }
}

I have a NavigationLink (named 'link') in a list cell. I would like for the Text within 'link' to be to the rightmost side of the view. To try to accomplish this, I inserted 'link' in an HStack and put a Spacer() before it to try and push it to the rightmost part of the view. When I run the app though, the Text ends up in between Text("1") and Text("2") and I can't figure out why. I want Text("1") to be in the leftmost part of the view, Text("2") to be in the center of the view, and 'link' to be in the rightmost part of the view. I have provided visuals (the colors aren't important, I just wanted to make the different Texts clear):

Desired layout:

enter image description here

What I get instead:

enter image description here

I found that if I take everything out of the List view I get my desired layout. Also, if I keep everything in the List view and replace the NavigationLink with a Button I get my desired layout. The goal is to get the desired layout without having to change either of these aspects.

For the sake of clarity, I didn't include the code for OtherView() as I don't think it's necessary for this question.

CodePudding user response:

The "quick" fix is to add fixedSize() to the NavigationLink

var link: some View {
    NavigationLink(destination: Text("OtherView()")) {
        Text("NLTitle")
    }
    .foregroundColor(.blue)
    .fixedSize()
}

That will allow the link to shrink.

  • Related