微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Swiftui使子视图在点击时填满整个屏幕,并封装到单个子视图中

如何解决Swiftui使子视图在点击时填满整个屏幕,并封装到单个子视图中

我有一个简单的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.widthUIApplication.shared.windows.first!.frame.height。使用这种方法,ButtonView占据了屏幕的大小。但是,出现的问题是,如果父级包含任何其他子视图作为ButtonView的同级,则它们会影响ButtonView本身的对齐方式。在这种情况下,Text("Some text that shouldn't be visible in fullscreen")最终在屏幕底部占据了一定的空间,我想是因为RootView将包含ButtonView()Text()vstack水平居中当vstack占用的屏幕空间超过屏幕上的可用空间时。 理想情况下,这些兄弟姐妹应该被隐藏或至少完全从可见区域推出。

Clicking the button gives it the right frame dimensions,but it is not  correctly aligned

我想到的一个纯SwiftUI解决方案可能会在ContentView()中使用一个名为全屏的@State布尔变量,并将某些闭包传递给ButtonView,以在单击时切换父级的全屏状态。但是,这意味着我没有将全屏的所有功能都封装到ButtonView中。现在,使用ButtonView()的任何人都必须手动确保只有当状态变量为false时,才有条件地显示视图层次结构中除ButtonView()之外的所有其他视图。

我有没有办法在SwiftUI或UIKit中做到这一点,以便ButtonView()占据屏幕的整个空间,并且其任何同级视图都被隐藏或至少从可见的位置推出屏幕?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。