如何检查视图是否显示在屏幕上? (Swift 5 和 SwiftUI)
How to check if a view is displayed on the screen? (Swift 5 and SwiftUI)
我的观点如下。我想知道它是否是屏幕上显示的视图。有实现这个的功能吗?
struct TestView: View {
var body: some View {
Text("Test View")
}
}
您可以在任何符合 View 协议的视图上使用 onAppear。
struct TestView: View {
@State var isViewDisplayed = false
var body: some View {
Text("Test View")
.onAppear {
self.isViewDisplayed = true
}
.onDisappear {
self.isViewDisplayed = false
}
}
func someFunction() {
if isViewDisplayed {
print("View is displayed.")
} else {
print("View is not displayed.")
}
}
}
您可以使用 GeometryReader 和 GeometryProxy 检查视图在全局范围内的位置。
struct CustomButton: View {
var body: some View {
GeometryReader { geometry in
VStack {
Button(action: {
}) {
Text("Custom Button")
.font(.body)
.fontWeight(.bold)
.foregroundColor(Color.white)
}
.background(Color.blue)
}.navigationBarItems(trailing: self.isButtonHidden(geometry) ?
HStack {
Button(action: {
}) {
Text("Custom Button")
} : nil)
}
}
private func isButtonHidden(_ geometry: GeometryProxy) -> Bool {
// Alternatively, you can also check for geometry.frame(in:.global).origin.y if you know the button height.
if geometry.frame(in: .global).maxY <= 0 {
return true
}
return false
}
我的观点如下。我想知道它是否是屏幕上显示的视图。有实现这个的功能吗?
struct TestView: View {
var body: some View {
Text("Test View")
}
}
您可以在任何符合 View 协议的视图上使用 onAppear。
struct TestView: View {
@State var isViewDisplayed = false
var body: some View {
Text("Test View")
.onAppear {
self.isViewDisplayed = true
}
.onDisappear {
self.isViewDisplayed = false
}
}
func someFunction() {
if isViewDisplayed {
print("View is displayed.")
} else {
print("View is not displayed.")
}
}
}
您可以使用 GeometryReader 和 GeometryProxy 检查视图在全局范围内的位置。
struct CustomButton: View {
var body: some View {
GeometryReader { geometry in
VStack {
Button(action: {
}) {
Text("Custom Button")
.font(.body)
.fontWeight(.bold)
.foregroundColor(Color.white)
}
.background(Color.blue)
}.navigationBarItems(trailing: self.isButtonHidden(geometry) ?
HStack {
Button(action: {
}) {
Text("Custom Button")
} : nil)
}
}
private func isButtonHidden(_ geometry: GeometryProxy) -> Bool {
// Alternatively, you can also check for geometry.frame(in:.global).origin.y if you know the button height.
if geometry.frame(in: .global).maxY <= 0 {
return true
}
return false
}