tom debout
tom debout

Reputation: 69

TopBar in Swift

I am learning swift but I have a problem. I would like to make a top bar that covers the entire top of the screen. The problem is now I have an error that I do not understand: "Value of optional type 'CGFloat?' must be unwrapped to a value of type 'CGFloat'"

I would like to have help thank you in advance

import Foundation

struct ContentView: View {
    var body: some View {
        VStack{
            TopBar()
            Spacer()
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
struct TopBar : View {
    var body : some View{

        VStack(spacing: 20){
            HStack{
                Text("News").font(.system(size: 20)).fontWeight(.semibold).foregroundColor(.white)
                
                Spacer()

            }
        }.padding()
        .padding(.top, UIApplication.shared.windows.last?.safeAreaInsets.top + 10) //line with error : Value of optional type 'CGFloat?' must be unwrapped to a value of type 'CGFloat'
        .background(Color("Color"))
    }
}```

Upvotes: 0

Views: 280

Answers (1)

jnpdx
jnpdx

Reputation: 52625

When you use .last? that question mark means that last may not exist -- so, you end up with an optional (CGFloat?) instead of a (non-optional) CGFloat.

You could use nil coalescing (the ?? operator -- https://www.hackingwithswift.com/example-code/language/what-is-the-nil-coalescing-operator) to provide a default value in the event that your original value was nil:

.padding(.top, (UIApplication.shared.windows.last?.safeAreaInsets.top ?? 0) + 10) 

However, you should be aware that SwiftUI does safe area padding for you -- you shouldn't actually need to do it yourself. If you want 10 pts of top padding below the safe area inset, just use .padding(.top, 10)

Update, based on comments:

struct TopBar : View {
    var body : some View {
        VStack(spacing: 20) {
            HStack{
                Text("News").font(.system(size: 20)).fontWeight(.semibold).foregroundColor(.white)
                Spacer()
            }
        }
        .background(Color.red.edgesIgnoringSafeArea(.top))
    }
}

Upvotes: 1

Related Questions