按下后退按钮时 SwiftUI 工具栏项目被剪裁

die*_*mer 8 ios swift swiftui swiftui-navigationlink swiftui-navigationview

我在 SwiftUI 中遇到了一种奇怪的行为,我似乎无法解决它。

鉴于以下简单的示例应用程序,我遇到了这种行为:工具栏项目在初始运行时正确呈现,但导航离开并返回它会被剪切。

在此输入图像描述

重新创建此示例代码:

内容视图.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
      NavigationView {
        
        NavigationLink(destination: View2()) {
          Text("Hello, world!")
            .padding()
            .navigationTitle("View 1")
            .toolbar {
              Circle()
                .fill(Color.red)
                .frame(width: 150, height: 150, alignment: .center)
            }
        }
      }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
Run Code Online (Sandbox Code Playgroud)

View2.swift

import SwiftUI

struct View2: View {
    var body: some View {
        Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/)
    }
}

struct View2_Previews: PreviewProvider {
    static var previews: some View {
        View2()
    }
}

Run Code Online (Sandbox Code Playgroud)

Asp*_*eri 7

It is clipped by navigation bar as seen on view debug below so it is just rendering issue (should be clipped always):

演示1

A possible solution is to use that widget (Circle in the case) above NavigationView and align it with toolbar item.

演示

Here is main part:

.toolbar {
    Color.clear
        .frame(width: 150)
        .overlay(GeometryReader {
            Color.clear.preference(key: ViewPointKey.self,
                                 value: [$0.frame(in: .global).center])
        })
}

//...

Circle().fill(Color.red)
    .frame(width: 150, height: 150)
    .position(x: pos.x, y: pos.y)     // << here !!

//...

.onPreferenceChange(ViewPointKey.self) {
    pos = $0.first ?? .zero
}
Run Code Online (Sandbox Code Playgroud)

Complete findings and code is here