【问题标题】:Setting a height in a View and ignoring safe top edge在视图中设置高度并忽略安全的顶部边缘
【发布时间】:2019-06-07 11:38:11
【问题描述】:

我想显示一个高度为屏幕高度一半的MKMapView,忽略顶部边缘。这是我的代码:

import SwiftUI
import MapKit

struct ContentView : View {
    var body: some View {
        VStack {
            MapView()
                .border(Color.red, width: 1)
                .edgesIgnoringSafeArea(.top)
          //      .frame(height: UIScreen.main.bounds.height / 2)

            Image("turtlerock")
                .clipShape(Circle())
                .overlay(Circle().stroke(Color.red, lineWidth: 1))

            Text("Test")
                .font(.title)

        }
    }
}

我注释掉了 frame 方法。这些是执行上述代码时的结果(左图),并且没有注释掉 frame 方法(右图):

我们可以检查左边的图像,所以如果没有 frame 方法,边缘会在顶部被忽略,这很好。在应用帧高方法的右图上,不再忽略顶部边缘。

据我了解,应用于视图的修饰符的顺序很重要。我尝试了各种命令,但我无法弄清楚如何使用屏幕高度的一半创建 MapView 视图并忽略顶部边缘。 MapView 结构体定义如下:

import MapKit
import SwiftUI

struct MapView : UIViewRepresentable {
    func updateUIView(_ uiView: MKMapView, context: Context) {
        let coordinate = CLLocationCoordinate2D(latitude: 34.011286, longitude: -116.166868)
        let span = MKCoordinateSpan(latitudeDelta: 2.0, longitudeDelta: 2.0)
        let region = MKCoordinateRegion(center: coordinate, span: span)

        uiView.setRegion(region, animated: true)
    }

    func makeUIView(context: Context) -> MKMapView {
        MKMapView(frame: .zero)
    }
}

【问题讨论】:

  • 你不应该改用relativeHeight(_:)吗?
  • @user28434 我也试过了,但它是相对于它的父高度。使用这种方法时,我得到了非常奇怪的高度。使用这种方法:MapView视图上的.relativeHeight(0.5),视图变得非常小...
  • 另外,您可以在顶视图上尝试.edgesIgnoringSafeArea(.top)
  • @user28434 是的,我已经这样做了,我包含了代码,以便人们可以在几秒钟内重现此视图

标签: swift swiftui


【解决方案1】:

原来我只需要在最后添加一个 Spacer():

struct ContentView : View {
    var body: some View {
        VStack {
            MapView()
                .border(Color.red, width: 1)
                .edgesIgnoringSafeArea(.top)
                .frame(height: UIScreen.main.bounds.height / 2)

            Image("turtlerock")
                .clipShape(Circle())
                .overlay(Circle().stroke(Color.red, lineWidth: 1))

            Text("Test")
                .font(.title)

            Spacer() // New line
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    • 1970-01-01
    • 2018-08-23
    • 1970-01-01
    • 2015-06-17
    相关资源
    最近更新 更多