Search code examples
swiftuilayouttoolbar

SwiftUI toolbar multiple items compression resistance


I have a toolbar with user info (leading alignment) and some buttons (trailing):

view
    .toolbar {
        ToolbarItem(placement: .navigationBarLeading) {
            VStack {
                Text("...")
                Text("...")
            }
        }
        ToolbarItem(placement: .navigationBarTrailing) {
            // buttons
        }
    }

Normally looks like this: enter image description here

But if the text is really long it takes up all the space and doesn't leave anything to the buttons. Like this: enter image description here

What I need is to specify compression resistance for buttons, so they always have enough space and text just takes what's left. How do I do that?


Solution

  • It looks like a bug of .navigationBarLeading placement, as a workaround it is possible to use .principal with spacer to align to the left of text is short

    Tested with Xcode 13.4 / iOS 15.5

    demo1 demo2

    ToolbarItem(placement: .principal) {   // << here !!
        HStack {
            VStack(alignment: .leading) {
                Text("Cosmic Serenity asdlkf ;asdfj kas;dlkf a;sdlfk asdkj")
                Text("Unreality")
            }
            Spacer()    // << here !!
        }
    }