I'm a newbie in SwiftUI and I want to create this card on the screen
I wrote this code snippet:
struct StakingCard: View {
var body: some View {
ZStack(alignment: .leading){
VStack(alignment: .leading){
Text("Staking CAKE").font(.headline)
.foregroundColor(.white)
Text("Stake tokens and get rewards")
.foregroundColor(.white)
}.frame(maxWidth: .infinity, maxHeight: 100)
.background(
Image("blac")
.resizable()
.scaledToFill())
.padding(0)
}.cornerRadius(10)
.padding(.horizontal,10)
}
}
But when I insert it into my Content view, I get the following Screen: The padding in the card is resizing and it does'not look good
Kindly direct me on how to go about this, thanks.
CodePudding user response:
It may be helpful to share the code for the whole view of the screen, and not just the individual component since there are many factors that could be causing the issue.
Most likely, the fix would be to set a fixed width on the view instead of using maxWidth: .infinity
. Because the view is inside of a container that is scrolling, it's impossible to figure out what the maximum width might be.
CodePudding user response:
A couple notes:
- The texts aren't padded because there's no
.padding
modifier on them (only.padding(0)
on the image and.padding(10)
on theZStack
) - If
.padding(10)
is the padding betweenStakingCard
's - that should be added by theHStack
the cards exist in, not the card itself. - Can get rid of the
ZStack
- theImage
is set as the background via the.background
modifier. - That
maxWidth: .infinity
isn't necessary, the cells are in a scrolling collection with unbounded width.
Here's an updated version:
struct StakingCard: View {
var body: some View {
VStack(alignment: .leading) {
Text("Staking CAKE")
.font(.headline)
.foregroundColor(.white)
Text("Stake tokens and get rewards")
.foregroundColor(.white)
}
.padding(.horizontal) // #1 - Texts padding
.frame(maxHeight: 100) // #4 - no maxWidth: .infinity
.background(
Image("blac")
.resizable()
.scaledToFill())
.cornerRadius(10)
}
}
struct StakingCard_Previews: PreviewProvider {
static var previews: some View {
// single card preview
StakingCard()
// collection preview
ScrollView(.horizontal) {
HStack(spacing: 10) { // #2 - padding between cells
StakingCard()
StakingCard()
}
.padding()
}
}
}