我是 Swift 的初学者,我知道这一定与“.”有关。就在“safeAreaInset”之前。但即使有了“自我”,它也不起作用。
我想仅在“if”条件下激活“safeAreaInset”。
import SwiftUI
import MapKit
struct ContentView: View {
var body: some View {
Map()
.safeAreaInset(edge: .top, alignment: .trailing) {
Text("Hi!")
.frame(maxWidth: .infinity, maxHeight: 80)// Breite und Höhe des Insets
.background (.thinMaterial)
}
}
}
我今天读了很多关于“自我”的内容,但我假设“自我”。仅引用实例而不引用视图?我还阅读了一些有关视图扩展的内容,但我不确定这是否是正确的(对于初学者来说也是最简单的)方法。或者我是否需要一个函数来实现这个?
将
if
包裹在安全区域插图的 contents 周围,
@State var flag = false
var body: some View {
Map()
.safeAreaInset(edge: .top, alignment: .trailing) {
if flag {
Text("Hi!")
.frame(maxWidth: .infinity, maxHeight: 80)
.background (.thinMaterial)
}
}
// just so you can toggle the flag and see the effect,
Toggle("Toggle", isOn: $flag)
}
当
flag
为 false 时,安全区域插入变为 EmptyView
,这实际上与根本没有安全区域插入相同。
请注意,编写这样的修饰符可能很诱人
extension View {
@ViewBuilder
func `if`<V>(_ condition: Bool, @ViewBuilder content: (Self) -> V) -> some View where V : View {
if condition {
content(self)
} else {
self
}
}
}
并像这样使用它:
Map()
.`if`(flag) {
$0.safeAreaInset(edge: .top, alignment: .trailing) {
Text("Hi!")
.frame(maxWidth: .infinity, maxHeight: 80)
.background (.thinMaterial)
}
}
需要注意的是,这将不会保留视图身份。每次条件发生变化时,它都会销毁
Map
并创建新的 Map
。这将导致 Map
的状态被重置。例如,相机位置将重置为初始位置。