繁体   English   中英

如何在 SwiftUI 的 TabView 中添加底部曲线?

[英]How to add a bottom curve in TabView in SwiftUI?

我只想在我的 tabView 中心有一条底部曲线,但我无法访问 tabView 形状属性。

最终图像

这就是我要的。

笔记:

曲线应始终保持在中心。 并且项目应该交换,这已经在给定的代码中实现。

import SwiftUI

struct DashboardTabBarView: View {

@State private var selection: String = "home"

struct Item {
    let title: String
    let color: Color
    let icon: String
}

@State var items = [
    Item(title: "cart", color: .red, icon: "cart"),
    Item(title: "home", color: .blue, icon: "house"),
    Item(title: "car", color: .green, icon: "car"),
]

var body: some View {

    TabView(selection: $selection) {
        ForEach(items, id: \.title) { item in // << dynamically !!
            item.color
                .tabItem {
                    Image(systemName: item.icon)
                    Text(item.title)
                }
        }
    }
    .onChange(of: selection) { title in // << reorder with centered item
        let target = 1
        if var i = items.firstIndex(where: { $0.title == title }) {
            if i > target {
                i += 1
            }
            items.move(fromOffsets: IndexSet(integer: target), toOffset: i)
        }
    }
}
}

好的,实际上我们需要在这里解决两个问题,首先 - 找到标签栏的高度,其次 - 正确地将视图自定义视图与标准标签栏上表示的选定项目对齐。 其他一切都是机械

这是简化的演示。 使用 Xcode 14 / iOS 16 进行测试。

演示

主要部分:

  • 问题 #1 的可能解决方案
struct TabContent<V: View>: View {
    @Binding var height: CGFloat
    @ViewBuilder var content: () -> V

    var body: some View {
        GeometryReader { gp in  // << read bottom edge !!
            content()
                .onAppear {
                    height = gp.safeAreaInsets.bottom
                }
                .onChange(of: gp.size) { _ in
                    height = gp.safeAreaInsets.bottom
                }
        }
    }
}
  • 问题 #2 的可能解决方案
    // Just put customisation in z-ordered over TabView
    ZStack(alignment: .bottom) {
        TabView(selection: $selection) {
            // .. content here
        }

        TabSelection(height: tbHeight, item: selected)
    }


struct TabSelection: View {
    let height: CGFloat
    let item: Item
    
    var body: some View {
        VStack {
            Spacer()
            Curve()    // put curve over tab bar !!
                .frame(maxWidth: .infinity, maxHeight: height)
                .foregroundColor(item.color)
        }
        .ignoresSafeArea()   // << push to bottom !!
        .overlay(
            // Draw overlay
            Circle().foregroundColor(.black)
                .frame(height: height).aspectRatio(contentMode: .fit)
                .shadow(radius: 4)
                .overlay(Image(systemName: item.icon)
                    .font(.title)
                    .foregroundColor(.white))
            , alignment: .bottom)
    }
}

测试模块在这里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM