user626776
user626776

Reputation:

SwiftUI how to center position an item in VStack

I have a simple view like this:

    let state = viewModel.state
    
    VStack {
    
      // "Come back tomorrow!" label
      Text(loc(.comeBackTomorrow))
        .withMainBodyStyle()
    
      if state.isRewardable && viewModel.isVideoAdReady {

        // "One more joke?" button
        SUIBorderedTextButton(
          title: loc(.oneMoreJokeButtonTitle),
          fontSize: font_size_one_more_joke_button,
          backgroundColor: color_one_more_joke_button,
          enabled: true)
        {
          AdUtil.showVideoAd()
        }
      }
    }

This code is the content region in this screenshot, excluding the toolbar on the bottom:

enter image description here

Note that "Come back tomorrow!" label is roughly positioned at 1/3 of the VStack, and "One more joke?" button is roughly at 2/3 of the VStack.

Now I need to position VStack items such that "Come back tomorrow!" label is in the center of the VStack, and "One more joke?" button is slightly below "Come back tomorrow!" label. How can I do that?

Edit:

I tried this code in the answer by @Asperi:

VStack {
  Spacer()

  Text("Label")    // << your label view here

  Spacer().overlay(Group {
     if condition {
        Button("Title") {}     // << your button here 
     }
  }, alignment: .top)

}

And got this result:

enter image description here

Upvotes: 1

Views: 721

Answers (1)

Asperi
Asperi

Reputation: 257693

A possible approach is to use Color.clear and overlay, like

VStack {
  Color.clear

  Text("Label")    // << your label view here

  Color.clear.overlay(Group {
     if condition {
        Button("Title") {}     // << your button here 
     }
  }, alignment: .top)

}

Upvotes: 1

Related Questions