我有一個視圖“TopTabBar”,我在兩個不同的螢屏中使用它。但是在一個螢屏中應該有 2 個按鈕,而在另一個螢屏中應該有 4 個。在通常的 swift 中,我將在此 TopTabBar 中創建一個函式,我將使用該函式將按鈕添加到堆疊中,并從我使用它的位置創建它們。但在 SwiftUI 中我不能這樣做。如何讓螢屏重復使用并從外部填充適量的按鈕?
import SwiftUI
struct TopBar: View {
var firstViewTitle: String
var secondViewTitle: String
var thirdViewTitle: String?
var fourthViewTitle: String?
@Binding var tabIndex: Int
var body: some View {
HStack(spacing: 0) {
TabBarButton(text: firstViewTitle, isSelected: .constant(tabIndex == 0))
.onTapGesture { onButtonTapped(index: 0) }
TabBarButton(text: secondViewTitle, isSelected: .constant(tabIndex == 1))
.onTapGesture { onButtonTapped(index: 1) }
TabBarButton(text: thirdViewTitle ?? "", isSelected: .constant(tabIndex == 2))
.onTapGesture { onButtonTapped(index: 2) }
TabBarButton(text: fourthViewTitle ?? "", isSelected: .constant(tabIndex == 3))
.onTapGesture { onButtonTapped(index: 3) }
}
.border(width: 1, edges: [.bottom], color: .lightGrey)
.frame(width: UIScreen.screenWidth, height: 50, alignment: .center)
}
private func onButtonTapped(index: Int) {
withAnimation { tabIndex = index }
}
}
struct TabBarButton: View {
let text: String
@Binding var isSelected: Bool
var body: some View {
Text(text)
.foregroundColor(isSelected ? .black : .gray)
.fontWeight(isSelected ? .heavy : .regular)
.padding(.bottom, 10)
.border(width: isSelected ? 2 : 0, edges: [.bottom], color: .black)
.frame(width: UIScreen.screenWidth/4, height: 50, alignment: .center)
.background(Color.random)
}
}
struct Usable: View {
@State var tabIndex = 0
var body: some View {
NavigationView {
ZStack {
if tabIndex == 1 {
debugPring("xxx")
}
VStack {
TopBar(firstViewTitle: "first", secondViewTitle: "second", thirdViewTitle: "third", fourthViewTitle: "fourth" ,tabIndex: $tabIndex).padding(.top, 20)
if tabIndex == 0 {
debugPrint("xxx")
}
Spacer()
}
}
.navigationBarHidden(true)
}.accentColor(Color.black)
}
}
uj5u.com熱心網友回復:
實際上有很多選擇,但是根據您當前的設計,可以使它們成為有條件的,例如
HStack(spacing: 0) {
TabBarButton(text: firstViewTitle, isSelected: .constant(tabIndex == 0))
.onTapGesture { onButtonTapped(index: 0) }
TabBarButton(text: secondViewTitle, isSelected: .constant(tabIndex == 1))
.onTapGesture { onButtonTapped(index: 1) }
if let title = thirdViewTitle {
TabBarButton(text: title, isSelected: .constant(tabIndex == 2))
.onTapGesture { onButtonTapped(index: 2) }
}
if let title = fourthViewTitle {
TabBarButton(text: title, isSelected: .constant(tabIndex == 3))
.onTapGesture { onButtonTapped(index: 3) }
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/477651.html
上一篇:將按鈕移動到中心
