mahan
mahan

Reputation: 14935

SwiftUI - Always left (leading) align navigationBarItems(leading: Text(""))

I have a NaivgationView that has dynamic Leading item. That is to say, when a user taps on a button, its text gets updated. So it is not always the same.

This code has similar function as of my project.

struct ContentView: View {
    @State var selectedDay: String = "Wednesday"
    let days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
    var body: some View {
        NavigationView {
            VStack {
                List {
                    ForEach(0..<days.count) {day in
                        Button(action: {
                            self.selectedDay = days[day]
                        }, label: {
                            Text(days[day])
                        })
                    }
                }
            }
            .navigationBarItems(leading: Text($selectedDay.wrappedValue))
        }
    }
}

I want that the text must be left aligned always. But if a text has fewer letters than the first one, it is not on the left. For example in the code above, Wednesday is on the very left edge, but friday is not. There is like 16 points on its leading side. So How to left align text?


I have used this code also but stil has the same issue.

VStack(alignment: .leading) {
     Text($selectedDay.wrappedValue)
}

Upvotes: 0

Views: 392

Answers (1)

nicksarno
nicksarno

Reputation: 4245

You can add a frame to the Text and set its alignment:

   .navigationBarItems(leading:
                            Text(selectedDay)
                                .frame(width: 100, alignment: .leading)
    )

Upvotes: 1

Related Questions