首页 > 解决方案 > 仅在满足条件时如何应用edgeIgnoringSafeAre?

问题描述

我有这个:

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

我想申请一个

.edgesIgnoringSafeArea(.top)

只要设备有缺口。

我创建了这个视图修饰符,但有各种错误。

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)
  }
}

函数声明了一个不透明的返回类型,但它的主体中没有返回语句来推断基础类型

调用“edgesIgnoringSafeArea”的结果未使用

“IgnoreTopSafeArea.Content”(又名“_ViewModifier_Content”)类型的表达式未使用

我怎么做?

标签: swiftui

解决方案


您几乎完成了,需要使用()并且您不需要该函数来读取缺口。

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

版本 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
}

版本 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)
            
        }
        
    }
}

适用于两个版本:

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

推荐阅读