[英]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 進行測試。
主要部分:
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
}
}
}
}
// 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.