选项卡栏不适合所有设备。我想我应该使用GHeometryReader,但我尝试过,失败了。
我通过改变偏移量(x:x)的所有图标,但它不是正确的解决方案,因为有很多不同的屏幕尺寸。
如何使选项卡栏适合所有屏幕尺寸?
下面的代码就是这样工作的:
struct TabBarView: View {
//Custom type
//Environnements
@Environment(\.colorScheme) private var colorScheme
//State or Binding String
@State private var icons: [String] = ["house.fill", "creditcard.fill", "plus", "dollarsign.circle.fill", "rectangle.stack.fill"]
//State or Binding Int, Float and Double
@Binding var selectedTab: Int
@State private var offsetSelectedTab: CGFloat = 0
var tabBarWidth = UIScreen.main.bounds.width - 20
//State or Binding Bool
//Enum
//Computed var
var tabItemWidth: CGFloat { return tabBarWidth / 5 }
@ViewBuilder
var indicator: some View {
Rectangle()
.foregroundColor(.white)
.cornerRadius(12)
.shadow(radius: 4, x: 0, y: 4)
.offset(x: CGFloat(selectedTab) * (tabBarWidth / 5) + 12, y: 0)
.animation(.spring(), value: selectedTab)
.frame(width: 50, height: 35)
}
//MARK: - Body
var body: some View {
ZStack(alignment: .leading) {
indicator
HStack {
IconTabBar(icon: "house.fill", selectedTabIndex: $selectedTab, onPressTabBarItem: {
withAnimation(.interpolatingSpring(stiffness: 170, damping: 30)) { selectedTab = 0 }
}, tabItemWidth: tabItemWidth)
IconTabBar(icon: "creditcard.fill", selectedTabIndex: $selectedTab, onPressTabBarItem: {
withAnimation(.interpolatingSpring(stiffness: 170, damping: 30)) { selectedTab = 1 }
}, tabItemWidth: tabItemWidth)
IconTabBar(icon: "plus", selectedTabIndex: $selectedTab, onPressTabBarItem: {
withAnimation(.interpolatingSpring(stiffness: 170, damping: 30)) { selectedTab = 2 }
}, tabItemWidth: tabItemWidth)
IconTabBar(icon: "dollarsign.circle.fill", selectedTabIndex: $selectedTab, onPressTabBarItem: {
withAnimation(.interpolatingSpring(stiffness: 170, damping: 30)) { selectedTab = 3 }
}, tabItemWidth: tabItemWidth)
IconTabBar(icon: "rectangle.stack.fill", selectedTabIndex: $selectedTab, onPressTabBarItem: {
withAnimation(.interpolatingSpring(stiffness: 170, damping: 30)) { selectedTab = 4 }
}, tabItemWidth: tabItemWidth)
}
.frame(width: tabBarWidth)
}
.padding(.vertical, 6)
.frame(width: tabBarWidth)
.background(Color.colorPastelBlue)
.cornerRadius(12)
.padding()
}//END body
//MARK: Fonctions
}//END struct
//MARK: - Preview
struct TabBarView_Previews: PreviewProvider {
@State static var selectedTabPreview: Int = 0
static var previews: some View {
TabBarView(selectedTab: $selectedTabPreview)
}
}
//MARK: ICON IN TABBAR
struct IconTabBar: View {
var icon: String
@Binding var selectedTabIndex: Int
var onPressTabBarItem: () -> Void
let tabItemWidth: CGFloat
var body: some View {
Button {
onPressTabBarItem()
} label: {
Image(systemName: icon)
.foregroundColor(.colorLabel)
.font(.system(size: 18, weight: .semibold, design: .rounded))
}
.frame(width: tabItemWidth, height: 35)
}
}
1条答案
按热度按时间nbewdwxp1#
下面是更新后的代码:
在这里我做了偏移量的改变。
还在IconTabBar中添加了Spacer。