简体   繁体   中英

GeometryReader Takes Extra Space in SwiftUI

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.

预览图像

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)

}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM