问题描述
我有一个简单的SwiftUI ButtonView,其中包含一个按钮。我希望ButtonView可以在点击时填满设备的整个屏幕。但是我希望所有执行屏幕填充的代码都封装在ButtonView中,因此任何包含ButtonView的SwiftUI视图都可以使用它来填充屏幕。这是我写的一些尝试代码。
import SwiftUI
struct ContentView: View {
var body: some View {
vstack {
ButtonView()
Text("Some text that shouldn't be visible in fullscreen")
.foregroundColor(Color.black)
.padding()
.background(Color.yellow)
}
}
}
struct ButtonView: View {
@State var isFullscreen = false
func getFrameWidth() -> CGFloat? {
if self.isFullscreen {
return CGFloat(UIApplication.shared.windows.first!.frame.width)
} else {
return nil
}
}
func getFrameHeight() -> CGFloat? {
if self.isFullscreen {
return CGFloat(UIApplication.shared.windows.first!.frame.height)
} else {
return nil
}
}
var body: some View {
let width = getFrameWidth()
let height = getFrameHeight()
let widthStr = width != nil ? width!.description : "default"
let heightStr = height != nil ? height!.description : "default"
return Button("WIDTH: \(widthStr),HEIGHT: \(heightStr)") {
self.isFullscreen.toggle()
}
.frame(width: width,height: height,alignment: .center)
.foregroundColor(Color.primary)
.background(Color.gray)
.animation(.easeIn)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
我的方法是使用@State var isFullscreen
跟踪按钮是否全屏显示。然后,我使用frame修饰符,并在其中调用函数以获取框架的宽度和高度。当按钮不在全屏模式时,宽度和高度返回nil,因此frame修改器只是简单地布置按钮文本并采用其包含的文本大小。但是,当按钮全屏显示时,函数将分别返回UIApplication.shared.windows.first!.frame.width
和UIApplication.shared.windows.first!.frame.height
。使用这种方法,ButtonView占据了屏幕的大小。但是,出现的问题是,如果父级包含任何其他子视图作为ButtonView的同级,则它们会影响ButtonView本身的对齐方式。在这种情况下,Text("Some text that shouldn't be visible in fullscreen")
最终在屏幕底部占据了一定的空间,我想是因为RootView将包含ButtonView()
和Text()
的vstack水平居中当vstack占用的屏幕空间超过屏幕上的可用空间时。
理想情况下,这些兄弟姐妹应该被隐藏或至少完全从可见区域推出。
我想到的一个纯SwiftUI解决方案可能会在ContentView()中使用一个名为全屏的@State布尔变量,并将某些闭包传递给ButtonView,以在单击时切换父级的全屏状态。但是,这意味着我没有将全屏的所有功能都封装到ButtonView中。现在,使用ButtonView()的任何人都必须手动确保只有当状态变量为false时,才有条件地显示视图层次结构中除ButtonView()之外的所有其他视图。
我有没有办法在SwiftUI或UIKit中做到这一点,以便ButtonView()占据屏幕的整个空间,并且其任何同级视图都被隐藏或至少从可见的位置推出屏幕?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)