swiftui - 仅在满足条件时如何应用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”)类型的表达式未使用
我怎么做?
解决方案
您几乎完成了,需要使用()并且您不需要该函数来读取缺口。
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 ()
}
}
推荐阅读
- android - 如何强制jetpack compose重组?
- reactjs - 反应未处理的拒绝(TypeError):无法读取未定义的属性“_internalPath”
- python-3.x - 使 django2exe python3.9 兼容
- php - Codeception 中的单元测试:如何将 Codeception 指向我的代码?
- java - 无法在 Java 中增加分贝(使用静音选项)
- python - 如何避免使用 pandas to_datetime 方法获取 SettingWithCopyWarning
- python - 将数据框的“Bump Instance”列拆分为多行,这样一行中只保留一个值
- python - 输入带有比较运算符的字符串,并在数组索引上执行比较
- python - AttributeError:模块“tf_util”没有属性“conv2d”
- html - DOMException 错误:Google Drive 是否仍支持带有 /preview 的嵌入链接?