我正在学习SwiftUI,在尝试构建应用程序时遇到了一个问题。我的问题是如何使一个选项卡栏在活动时改变systemImage
(当home键处于活动状态时,它显示"home.fill",当用户按下搜索按钮时,home键更改为"home")。
import SwiftUI
struct ContentView: View {
@State private var fullScreenCover = false
init() {
UITabBar.appearance().isTranslucent = false
}
var body: some View {
VStack {
ForEach(0..<6) { num in
Spacer()
}
HStack {
Spacer()
Button(action: {}, label: {
Image(systemName: "message")
.font(.system(size: 20))
})
.padding(.horizontal, 15)
}
.foregroundColor(Color("Reverse"))
.padding(.vertical, 8)
TabView {
Main_Home()
.tabItem {
Image(systemName: "house")
.font(.system(size: 30))
}
Main_Search()
.tabItem {
Image(systemName: "magnifyingglass")
.font(.system(size: 30))
}
Main_AddContent()
.tabItem {
Image(systemName: "plus.viewfinder")
.font(.system(size: 30))
}
Main_Message()
.tabItem {
Image(systemName: "pencil.circle.fill")
.font(.system(size: 30))
}
Main_Profile()
.tabItem {
Image(systemName: "person.crop.circle")
.font(.system(size: 30))
}
}
.accentColor(Color("Reverse"))
}
.background(Color("Normal"))
.edgesIgnoringSafeArea(.all)
}
}
下面是一个您可以用来添加制表项的自定义ViewModifier
:
public struct TabViewItem<SelectionValue>: ViewModifier where SelectionValue: Hashable {
@Binding private var selectedIndex: SelectionValue
private let index: SelectionValue
private let text: String
private let imageName: String
public init(selectedIndex: Binding<SelectionValue>, index: SelectionValue, text: String, imageName: String) {
self._selectedIndex = selectedIndex
self.index = index
self.text = text
self.imageName = imageName
}
public func body(content: Content) -> some View {
content
.tabItem {
image
Text(text)
}
.tag(index)
}
private var image: some View {
guard selectedIndex == index else {
return Image(systemName: imageName)
}
let imageName = self.imageName + ".fill"
if let uiImage = UIImage(systemName: imageName) {
return Image(uiImage: uiImage)
}
return Image(systemName: self.imageName)
}
}
public extension View {
func tabItem<Selection>(
_ text: String,
imageName: String,
index: Selection,
selection: Binding<Selection>
) -> some View where Selection: Hashable {
modifier(TabViewItem(selectedIndex: selection, index: index, text: text, imageName: imageName))
}
}
然后,创建TabView
更直接:
struct ContentView: View {
@State private var selectedTab = 3
var body: some View {
TabView(selection: $selectedTab) {
Text("Main_Home")
.tabItem("Home", imageName: "house", index: 1, selection: $selectedTab)
Text("Main_Search")
.tabItem("Search", imageName: "magnifyingglass", index: 2, selection: $selectedTab)
Text("Main_AddContent")
.tabItem("AddContent", imageName: "plus.viewfinder", index: 3, selection: $selectedTab)
Text("Main_Message")
.tabItem("Message", imageName: "pencil.circle", index: 4, selection: $selectedTab)
Text("Main_Profile")
.tabItem("Profile", imageName: "person.crop.circle", index: 5, selection: $selectedTab)
}
}
}
注意:上面的实现是通用的目的-如果你不需要某些部分(如text
在制表符),只需删除它或使它们成为可选的