3

The code below is to create a custom button

import SwiftUI

let skyBlue = Color(red: 75/255, green: 170/255, blue: 193/255)

struct RegisterButtonView: View {
    var body: some View {
        GeometryReader { geo in
            HStack {
                Spacer()

                Text("Register")
                    .foregroundColor(Color(.white))
                    .font(.system(size: geo.size.width / 20))
                    .bold()

                Spacer()
            }
            .frame(width: geo.size.width * 4/9, height: geo.size.height / 7)
            .background(skyBlue)
            .cornerRadius(60)
        }

    }
}

struct RegisterButtonView_Previews: PreviewProvider {
    static var previews: some View {
        RegisterButtonView()
    }
}

However, the whole button view contains the extra space introduced by the GeometryReader, so that when I put this view to a root view, the space cannot be eliminated.

Image for Preview

SecretAgentMan
  • 2,856
  • 7
  • 21
  • 41
Lance Chan
  • 31
  • 1
  • 2
  • 1
    Welcome on board. It is not extra space - `GeometryReader` does consume **all** available space. That's a feature. – Asperi Feb 28 '20 at 17:31
  • Thanks, but is it possible that I can make my RegisterButtonView only contain its shape without the white space? (In case I have to use GeometryReader) – Lance Chan Feb 28 '20 at 18:39
  • 1
    The problem is that the size of the `RegisterButtonView` is based on the size of the `Text`, and the size of the `Text` is based on its font size, and the font size is based on the size of the `GeometryReader`. `GeometryReader` takes all the size given to it by its parent. In this case, the parent is the root view. So tell us what you want the size of the `RegisterButtonView` to be based on, if not on the size of the `GeometryReader`? – rob mayoff Feb 29 '20 at 05:08
  • I actually want its size to be based on the shape of the button, which I think is the `HStack`. – Lance Chan Feb 29 '20 at 15:20

1 Answers1

0

You may need to set the frame of GeoReader directly.

    struct RegisterButtonView: View {
var body: some View {
    GeometryReader { geo in
        HStack {
            Spacer()

            Text("Register")
                .foregroundColor(Color(.white))
                .font(.system(size: geo.size.width / 20 * 9 / 4))
                .bold()

            Spacer()
        }
        .frame(width: geo.size.width , height: geo.size.height )
        .background(skyBlue)
        .cornerRadius(60)
    }.frame(width: UIScreen.main.bounds.width * 4/9 , height: UIScreen.main.bounds.height / 7)

}
}
E.Coms
  • 11,065
  • 2
  • 23
  • 35