Duck
Duck

Reputation: 35993

How to apply edgesIgnoringSafeAre just if a condition is satisfied?

I have this:

extension UIDevice {
  
  static func hasNotch() -> Bool {
    let bottom = UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.safeAreaInsets.bottom ?? 0
    return bottom > 0
  }
}

I want to apply a

.edgesIgnoringSafeArea(.top)

just if a device has notch.

I have created this view modifier, with all sort of errors.

struct IgnoreTopSafeArea: ViewModifier {
    
  func body(content: Content) -> some View {
    if UIDevice.hasNotch() {
      content
        .edgesIgnoringSafeArea(.top)
    } else {
      content
    }   
  }
}

extension View {
  func ignoreTopSafeArea() -> some View {
    self.modifier(IgnoreTopSafeArea)
  }
}

Function declares an opaque return type, but has no return statements in its body from which to infer an underlying type

Result of call to 'edgesIgnoringSafeArea' is unused

Expression of type 'IgnoreTopSafeArea.Content' (aka '_ViewModifier_Content') is unused

how do I do that?

Upvotes: 3

Views: 451

Answers (1)

swiftPunk
swiftPunk

Reputation: 1

You done it almost, need using () and you do not need that func for reading notch.

struct ContentView: View {
    
    var body: some View {
        
        Color.red
            .ignoreTopSafeArea()
  
    }
}

Version 1:

struct IgnoreTopSafeArea: ViewModifier {
    
    func body(content: Content) -> some View {
        
        return Group {
            
            if hasNotch() {
                content
                    .edgesIgnoringSafeArea(.top)
            } else {
                content
            }
            
        }
        
    }
    

}

func hasNotch() -> Bool {
    let bottom = UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.safeAreaInsets.bottom ?? 0
    return bottom > 0
}

Version 2:

struct IgnoreTopSafeArea: ViewModifier {
    
    func body(content: Content) -> some View {
        
        return GeometryReader { geometry in
            
            Group {
                
                if geometry.safeAreaInsets.bottom > 0 {
                    content
                        .edgesIgnoringSafeArea(.top)
                }
                else {
                    content
                }
            }
            .position(x: geometry.size.width/2, y: geometry.size.height/2)
            
        }
        
    }
}

Works for Both Version:

extension View {
    func ignoreTopSafeArea() -> some View {
        self.modifier(IgnoreTopSafeArea())  // <<: here ()
    }
}

Upvotes: 3

Related Questions