当视图是层次结构的一部分时,onAppear
onDisappear
修饰符可以被多次调用。
我知道有一个技巧,使一个onLoad
ViewModifier像这样
extension View {
func onLoad(perform action: (() -> Void)? = nil) -> some View {
self.modifier(ViewDidLoadModifier(action: action))
}
}
struct ViewDidLoadModifier: ViewModifier {
@State private var viewDidLoad = false
let action: (() -> Void)?
func body(content: Content) -> some View {
content
.onAppear {
if viewDidLoad == false {
viewDidLoad = true
action?()
}
}
}
}
字符串
从上面的代码中,onLoad
只会被调用一次
struct MyView: View {
var body: some View {
Text("Hello View")
.onAppear {
// may print multiple times
print("onAppear")
}
.onLoad {
// only prints once
// when the view first appears in the hierarchy
print("onLoad")
}
}
}
型
有没有一种方法可以有一个onUnLoad
ViewModifier?
struct MyView: View {
var body: some View {
Text("Hello View")
.onDisappear {
// may print multiple times
print("onDisappear")
}
.onUnLoad {
// only prints once,
// when the view is completely removed
print("onUnLoad")
}
}
}
型
1条答案
按热度按时间iklwldmw1#
我找到了一种方法来创建
onUnload
ViewModifier,将UIView
Package 在UIViewRepresentable
中,并使用其willMove(toSuperview:)
事件字符串
在UIKit中,如果调用了视图的
willMove(toSuperview:)
方法,并且toSuperview
为nil,则意味着将从层次结构中完全删除UIView。型