Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give shadow with cornerRadius to a Button in SwiftUI

Tags:

ios

swift

swiftui

I'm trying to give a shadow to Button using following code.

Code:

Button(action: {

            }) {
                Text("SIGN IN")
                    .font(.system(size: 17))
                    .fontWeight(.bold)
                    .foregroundColor(.green)
                    .frame(minWidth: 0, maxWidth: .infinity)
                    .padding()
                    .background(Color.white)
                    .clipped()
                    .overlay(
                        RoundedRectangle(cornerRadius: 25)
                           .stroke(lineWidth: 1)
                           .foregroundColor(.white)
                    )

            }
            .shadow(color: .gray, radius: 2, x: 0, y: 2)

Output:

enter image description here

In above image you can see that shadow is not proper.

How can I achieve the following?

enter image description here

like image 397
Mahendra Avatar asked Nov 19 '19 11:11

Mahendra


3 Answers

I would do it like this

Note: the last .padding is not important, depending on where and how the button will be placed, here is just for demo.

button

Button(action: {

}) {
    Text("SIGN IN")
        .font(.system(size: 17))
        .fontWeight(.bold)
        .foregroundColor(.green)
        .frame(minWidth: 0, maxWidth: .infinity)
        .padding()
        .background(
            RoundedRectangle(cornerRadius: 25)
                .fill(Color.white)
                .shadow(color: .gray, radius: 2, x: 0, y: 2)
    )
    .padding()
}
like image 120
Asperi Avatar answered Nov 19 '22 13:11

Asperi


Instead of setting the shadow to the Button directly try setting the shadow to your overlay like this:

    Button(action: {

    }) {
        Text("SIGN IN")
            .font(.system(size: 17))
            .fontWeight(.bold)
            .foregroundColor(.green)
            .frame(minWidth: 0, maxWidth: .infinity)
            .padding()
            .background(Color.white)
            .clipped()
            .overlay(
                RoundedRectangle(cornerRadius: 25)
                    .stroke(lineWidth: 1)
                    .foregroundColor(.white)
                    .shadow(color: .gray, radius: 2, x: 0, y: 2)
        )

    }

Let me know if it helps!

like image 42
Teetz Avatar answered Nov 19 '22 12:11

Teetz


Use this if you only want the shadow to be on the bottom of your button.

   Button(action: {

        }) {
            Text("SIGN IN")
                .font(.system(size: 17))
                .fontWeight(.bold)
                .foregroundColor(.green)
                .frame(minWidth: 0, maxWidth: .infinity)
                .padding()
                .background(Color.white)
                .cornerRadius(25)
                .shadow(color: .gray, radius: 2, x: 0, y: 2)
        }
like image 2
KevinP Avatar answered Nov 19 '22 13:11

KevinP