Why scaleToFill not filling the whole screen? - swiftui

I would like to use an image as the background of the app.
struct DetailView: View {
var borderWidth: CGFloat = 0
var body: some View {
// ZStack: Background, ScrollView(vertical)
ZStack {
Image("background_green").resizable().scaledToFill().opacity(0.8)
.frame(width:UIScreen.main.bounds.width, height:UIScreen.main.bounds.height)
VStack {
}.frame(width: UIScreen.main.bounds.width, height:UIScreen.main.bounds.height)
}
}
}
How come there are still some white space at the top?

You should ignore safe area, like
var body: some View {
// ZStack: Background, ScrollView(vertical)
ZStack {
Image("background_green").resizable().scaledToFill().opacity(0.8)
.edgesIgnoringSafeArea(.all) // << here !!
VStack {
}.frame(width: UIScreen.main.bounds.width, height:UIScreen.main.bounds.height)
}
}

Related

SwiftUI - How to change the background Color of top safe area to gray?

I want to change the background color of top safe area from green to gray. I have looked everywhere but could not find any solution. The screen in preview looks like this.
My codes:
struct ContentView: View {
#State var name = ""
init() {
//Use this if NavigationBarTitle is with Large Font
UINavigationBar.appearance().largeTitleTextAttributes = [.foregroundColor: UIColor.red]
UINavigationBar.appearance().backgroundColor = .gray
}
var body: some View {
NavigationView {
ZStack{
VStack{
TextField("Name", text: $name)
.frame(height:200)
.padding()
.background(backgrounImage())
.overlay(RoundedRectangle(cornerRadius: 20).stroke(Color.gray,lineWidth: 4))
.padding()
Spacer()
}.navigationTitle("Tanvir")
.background(Color.green.edgesIgnoringSafeArea(.all))
}
}
}
}
You can add another view on top of the ZStack:
var body: some View {
NavigationView {
ZStack(alignment: .top) { // <- Don't forget this
,,,
GeometryReader { reader in
Color.yellow
.frame(height: reader.safeAreaInsets.top, alignment: .top)
.ignoresSafeArea()
}
}
}
}
Don't forget the stack alignment!
Consistant Bar for the entire App
If you need it to be on all of your views, try putting the code somewhere more consistent like where you are providing the contentView:
#main
struct SwiftUIAppPlaygroundApp: App {
var body: some Scene {
WindowGroup {
ZStack {
ContentView()
GeometryReader { reader in
Color.yellow
.frame(height: reader.safeAreaInsets.top, alignment: .top)
.ignoresSafeArea()
}
}
}
}
}
Use this UIApplication extension to chagne your status bar color
extension UIApplication {
/**
Get status bar view
*/
var statusBarUIView: UIView? {
let tag = 13101996
if let statusBar = self.windows.first?.viewWithTag(tag) {
self.windows.first?.bringSubviewToFront(statusBar)
return statusBar
} else {
let statusBarView = UIView(frame: UIApplication.shared.windows.first?.windowScene?.statusBarManager?.statusBarFrame ?? .zero)
statusBarView.tag = tag
self.windows.first?.addSubview(statusBarView)
return statusBarView
}
}
}
Usage
struct ContentViewStatusBar: View {
#State var name = ""
init() {
//Use this if NavigationBarTitle is with Large Font
UINavigationBar.appearance().largeTitleTextAttributes = [.foregroundColor: UIColor.red]
UINavigationBar.appearance().backgroundColor = .gray
}
var body: some View {
NavigationView {
ZStack{
VStack{
TextField("Name", text: $name)
.frame(height:200)
.padding()
.background(backgrounImage())
.overlay(RoundedRectangle(cornerRadius: 20).stroke(Color.gray,lineWidth: 4))
.padding()
Spacer()
}.navigationTitle("Tanvir")
.background(Color.green.edgesIgnoringSafeArea(.all))
}
}.onAppear {
UIApplication.shared.statusBarUIView?.backgroundColor = .gray //<<=== Here
}
}
}

SwiftUI measuring the height of a view

I tried measuring the height of a view by using coordinatespace on it but the value it returns is the height of the full screen. Any idea why my code isn't giving me what I want ?
struct GeoReader: View {
var body: some View {
GeometryReader { geo in
VStack {
ZStack {
Rectangle()
.foregroundColor(.blue)
Text("Heigt of full screen is \(geo.size.height)")
}
ZStack {
Rectangle()
.foregroundColor(.red)
.coordinateSpace(name: "Redbox")
Text("Height of red box is \(geo.frame(in: .named("Redbox")).height)")
}
}
}
}
}
The showing size is the dimension of the full view that is the container of the inner view.
You need to use another GeometryReader to get the inner dimension of a second ZStack.
struct ContentView: View {
var body: some View {
GeometryReader { geo in
VStack {
ZStack {
Rectangle()
.foregroundColor(.blue)
Text("Heigt of full screen is \(geo.size.height)")
}
GeometryReader { innterGeo in //<Here
ZStack {
Rectangle()
.foregroundColor(.red)
.coordinateSpace(name: "Redbox")
Text("Height of red box is \(innterGeo.frame(in: .named("Redbox")).height)")
}
}
}
}
}
}
if you need to use this in any places then you can use this approch.
First, create one struct and wrapped your content with GeometryReader.
struct GeometryContentSize<Content: View>: View {
public var content: (CGSize) -> Content
var body: some View {
GeometryReader { geo in
content(geo.size)
}
}
}
usage:
struct ContentView: View {
var body: some View {
GeometryReader { geo in
VStack {
ZStack {
Rectangle()
.foregroundColor(.blue)
Text("Heigt of full screen is \(geo.size.height)")
}
GeometryContentSize { (size) in //<--- Here
ZStack {
Rectangle()
.foregroundColor(.red)
Text("Height of red box is \(size.height)")
}
}
}
}
}
}
The geometry reader measures the entires screen, because you put the geometry reader right on top in the body of the view. It will therefore read the geometry of the view it returns. In this case the entire screen.
If you want to get the size of the two rectangles, you schoul put the geometry reader in the Stack of the rectangle and the text.
struct GeoReader: View {
var body: some View {
GeometryReader { geo1 in
VStack {
ZStack {
Rectangle()
.foregroundColor(.blue)
Text("Heigt of full screen is \(geo1.size.height)")
}
ZStack {
GeometryReader { geo2 in
Rectangle()
.foregroundColor(.red)
.coordinateSpace(name: "Redbox")
Text("Height of red box is \(geo2.frame(in: .named("Redbox")).height)")
}
}
}
}
}
}

How to layout properly in ZStack (I have visibility problem)?

Here is reproducable small code below;
As you'll see when you run the demo code, the Element view does stay under Color.blue when dragged eventhough its above according to ZStack. By the way I also played with zIndex modifier but still no luck. Any solution you offer? Thanks all.
struct ContentView: View {
var body: some View {
GeometryReader { gr in
ZStack {
Color.blue.opacity(0.3)
.aspectRatio(1, contentMode: .fit)
.frame(width: gr.size.width)
VStack {
Spacer()
ScrollView(.horizontal) {
HStack {
ForEach(1...15, id: \.self) { (idx) in
Element(index: idx)
}
}
.padding()
}
.background(Color.secondary.opacity(0.3))
}
}
}
}
}
struct Element: View {
#State private var dragAmount = CGSize.zero
var index: Int
var body: some View {
Rectangle()
.frame(width: 80, height: 80)
.overlay(Text("\(index)").bold().foregroundColor(.white))
.offset(dragAmount)
.gesture(
DragGesture(coordinateSpace: .global)
.onChanged {
self.dragAmount = CGSize(width: $0.translation.width, height: $0.translation.height)
}
.onEnded { _ in
self.dragAmount = .zero
}
)
}
}
iOS 15.5: still valid
How can achieve my goal then, like dragging Element on different view (in this scenario Color.blue)
Actually we need to disable clipping by ScrollView.
Below is possible approach based on helper extensions from my other answers (https://stackoverflow.com/a/63322713/12299030 and https://stackoverflow.com/a/60855853/12299030)
VStack {
Spacer()
ScrollView(.horizontal) {
HStack {
ForEach(1...15, id: \.self) { (idx) in
Element(index: idx)
}
}
.padding()
.background(ScrollViewConfigurator {
$0?.clipsToBounds = false // << here !!
})
}
.background(Color.secondary.opacity(0.3))
}

Size a SwiftUI view to be safeAreaInsets.top + 'x'

I am trying to create a full bleed SwiftUI 'header' view in my scene. This header will sit within a List or a scrollable VStack.
In order to do this, I'd like to have my text in the header positioned below the safe area, but the full view should extend from the top of the screen (and thus, overlap the safe area). Here is visual representation:
V:[(safe-area-spacing)-(padding)-(text)]
here is my attempt:
struct HeaderView: View {
#State var spacing: CGFloat = 100
var body: some View {
HStack {
VStack(alignment: .leading) {
Rectangle()
.frame(height: spacing)
.opacity(0.5)
Text("this!").font(.largeTitle)
Text("this!").font(.headline)
Text("that!").font(.subheadline)
}
Spacer()
}
.frame(maxWidth: .infinity)
.background(Color.red)
.background(
GeometryReader { proxy in
Color.clear
.preference(
key: SafeAreaSpacingKey.self,
value: proxy.safeAreaInsets.top
)
}
)
.onPreferenceChange(SafeAreaSpacingKey.self) { value in
self.spacing = value
}
}
}
This however, does not seem to correctly size 'Rectangle'. How can I size a view according to the safe area?
Is this what you're looking for? I try to avoid using GeometryReader unless you really need it... I created a MainView, which has a background and a foreground layer. The background layer will ignore the safe areas (full bleed) but the foreground will stay within the safe area by default.
struct HeaderView: View {
var body: some View {
HStack {
VStack(alignment: .leading) {
Text("this!").font(.largeTitle)
Text("this!").font(.headline)
Text("that!").font(.subheadline)
}
Spacer(minLength: 0)
}
}
}
struct MainView: View {
var body: some View {
ZStack {
// Background
ZStack {
}
.frame(maxWidth:. infinity, maxHeight: .infinity)
.background(Color.red)
.edgesIgnoringSafeArea(.all)
// Foreground
VStack {
HeaderView()
Spacer()
}
}
}
}
add an state to store desired height
#State desiredHeight : CGFloat = 0
then on views body :
.onAppear(perform: {
if let window = UIApplication.shared.windows.first{
let phoneSafeAreaTopnInset = window.safeAreaInsets.top
desiredHeight = phoneSafeAreaTopnInset + x
}
})
set the desiredHeight for your view .
.frame(height : desiredHeight)

SwiftUI popover background color

With UIKit, I could customize the background color of a popover using UIPopoverPresentationController's backgroundColor.
This would change the color including the arrow.
How can I accomplish this with SwiftUI? When I change the the popover content's background color, it doesn't include the arrow:
You can use .scaleEffect(…) to make your background view take more space. When it’s bigger than the content of the popover, it will fill the arrow.
struct ContentView: View {
#State var popoverVisible = false
var body: some View {
VStack {
Button("Open Popover") {
self.popoverVisible = true
}
.popover(isPresented: $popoverVisible) {
ZStack {
// Scaled-up background
Color.blue
.scaleEffect(1.5)
Text("Hello world")
.foregroundColor(.white)
.padding()
}
}
}
}
}
Use i.e. a VStack to fill the view, and then background will be extrapolated from the view at the edge:
struct ContentView: View {
#State var popoverVisible = false
var body: some View {
VStack {
Button("Open Popover") {
self.popoverVisible = true
}
.popover(isPresented: $popoverVisible) {
VStack {
Text("Hello world")
.foregroundColor(.white)
.padding(8)
Spacer()
Text("Bye world")
.foregroundColor(.white)
.background(Color.blue)
}
}
}
}
}