swiftuihstack

SwiftUI stop Divider from expanding vertically in HStack


I'm using SwiftUI to create something like an alert popup, which I present from UIKit code using UIHostingController. The view looks like this:

VStack(spacing: 0) {
    // Some text ...   

    HStack(spacing:0) {
        Button(action: self.onCancel) { Text("Cancel") }
           .padding().inExpandingRectangle().fixedSize(horizontal: false, vertical: true)

        // This divider is the problem
        Divider() // .fixedSize()

        Button(action: self.onDelete) {  Text("Delete") }
           .padding().inExpandingRectangle().fixedSize(horizontal: false, vertical: true)
    }
}.frame(minHeight: 0)

The inExpandingRectangle is something I found in another stackoverflow question. It centers the text in each side of the HStack.

extension View {
    func inExpandingRectangle() -> some View {
        ZStack {
            Rectangle().fill(Color.clear)
            self
        }
    }
}

It looks like this. Garbage.

enter image description here

If I put the .fixedSize() on the divider, it does this. Not horrible, but the divider is stupid looking and doesn't expand to the size of the buttons.

enter image description here


Solution

  • Here is a demo of possible simplified alternate, without that artificial extension. Tested with Xcode 11.4 / iOS 13.4.

    demo

    Divider() // or Rectangle().fill(Color.gray).frame(height: 1)
    HStack {
        Button(action: {}) { Text("Cancel").fixedSize() }
            .padding().frame(maxWidth: .infinity)
    
        Divider() // or Rectangle().fill(Color.gray).frame(width: 1)
    
        Button(action: {}) {  Text("Delete").fixedSize() }
            .padding().frame(maxWidth: .infinity)
    
    }.fixedSize(horizontal: false, vertical: true)
    

    Note: It worth also to consider custom divider, like

    Rectangle().fill(Color.gray).frame(width: 1) // or any other color
    

    than might give much appropriate visual feedback, like

    demo2