Home > OS >  ContentView not expanding outside of overlay - SwiftUI
ContentView not expanding outside of overlay - SwiftUI

Time:01-15

I want to display a view as a popup/tooltip from a view. I beleive the best way to acheive this is by presenting it as an overlay. But, the view is not expanding outside of bounds of where its being presented.

import SwiftUI

struct ContentView: View {
    let message = "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like)"

    var body: some View {
        VStack {
            Button {

            } label: {
                Text("Tap Me")
                    .background(
                        Rectangle()
                            .fill(.red)
                    )
            }
            .overlay {
                contentView
            }
        }
        .padding()
    }

    var contentView: some View {
        Text(message)
            .foregroundColor(Color.white)
            .padding()
            .background(Color.black)
            .foregroundColor(Color.white)
            .clipShape(RoundedRectangle(cornerRadius: 5))
            .offset(y: 60)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        return ContentView()
    }
}

enter image description here

Why is the contentView not expanding outside of the view from where it is being overlayed in my SwiftUI code?

I tried setting fixedSize, frame(maxWidth, but none of them have correct behaviour.

CodePudding user response:

The .overlay modifier always takes the size of its parent view as its maximum size. To put any size view in front of another, you should use a ZStack, e.g.

            ZStack {
                Button {

                } label: {
                    Text("Tap Me")
                        .background(
                            Rectangle()
                                .fill(.red)
                        )
                }
                contentView
            }

This is what it looks like (with .opacity applied)

enter image description here

  • Related