【问题标题】:How to apply edgesIgnoringSafeAre just if a condition is satisfied?仅在满足条件时如何应用edgeIgnoringSafeArea?
【发布时间】:2021-03-25 11:08:57
【问题描述】:

我有这个:

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


    【解决方案1】:

    你几乎做到了,需要使用 () 并且你不需要那个函数来读取缺口。

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

    【讨论】:

      猜你喜欢
      • 2019-05-06
      • 2017-07-06
      • 2017-12-12
      • 2018-06-17
      • 2018-01-22
      • 1970-01-01
      • 2016-10-22
      • 1970-01-01
      • 2018-08-07
      相关资源
      最近更新 更多