我有两个标签:“主要”和“朋友”。朋友有一个人的名单,我可以单击人以导航到他们的个人资料。
我想完成两件事:
我已经完成了#1的任务,但是没有动画过渡。不确定如何完成第二项。
enum Tab {
case home, friends
}
struct ContentView: View {
@State var tab: Tab = .home
@State var selectedFriend: String?
@State var friends: [String] = ["Mark", "Spencer"]
var body: some View {
TabView(selection: $tab) {
NavigationView {
VStack {
Button("You have a new friend Mark! Click to see his profile.") {
tab = .friends
selectedFriend = "Mark"
}
}
}
.tabItem {
Label("Home", systemImage: "list.bullet")
}
.tag(Tab.home)
NavigationView {
FriendsList(selected: $selectedFriend, friends: friends)
}
.tabItem {
Label("Friends", systemImage: "list.bullet")
}
.tag(Tab.friends)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct FriendsList: View {
@Binding var selected: String?
var friends: [String]
var body: some View {
VStack {
ForEach(friends, id:\.self) { friend in
NavigationLink(destination: FriendDetails(name: friend), tag: friend, selection: $selected) { EmptyView() }
}
List {
ForEach(friends, id:\.self) {friend in
Button(friend) {
self.selected = friend
}
}
}
}
}
}
struct FriendDetails: View {
var name: String
var body: some View {
Text("details of \(name)")
}
}
答案 0 :(得分:0)
这对我有用。添加了.listStyle(PlainListStyle())
以删除填充(我认为它看起来更好)
import SwiftUI
enum Tab {
case home, friends
}
struct ContentView: View {
@State var tab: Tab = .home
@State var selectedFriend: String?
@State var friends: [String] = ["Mark", "Spencer"]
@State var showFriendDetail = false
var body: some View {
TabView(selection: $tab) {
NavigationView {
VStack {
NavigationLink(destination: FriendDetails(name: selectedFriend ?? "Unknown"), isActive: $showFriendDetail) { EmptyView() }
Button("You have a new friend Mark! Click to see his profile.") {
selectedFriend = "Mark"
showFriendDetail = true
}
}
}
.tabItem {
Label("Home", systemImage: "list.bullet")
}
.tag(Tab.home)
NavigationView {
FriendsList(friends: friends)
}
.tabItem {
Label("Friends", systemImage: "list.bullet")
}
.tag(Tab.friends)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct FriendsList: View {
@State var selected: String?
var friends: [String]
var body: some View {
VStack {
ForEach(friends, id:\.self) { friend in
NavigationLink(destination: FriendDetails(name: friend), tag: friend, selection: $selected) { EmptyView() }
}
List {
ForEach(friends, id:\.self) {friend in
Button(friend) {
self.selected = friend
}
}
}.listStyle(PlainListStyle())
}
}
}
struct FriendDetails: View {
var name: String
var body: some View {
Text("details of \(name)")
}
}
答案 1 :(得分:-1)
在“主页”选项卡上,关闭“按钮”并改用NavigationLink。 NavigationLinks是从左向右推动并内置默认后退按钮的按钮。
TabView(selection: $tab) {
NavigationView {
VStack {
NavigationLink(
destination: FriendDetails(name: "Mark"),
label: {
Text("You have a new friend Mark! Click to see his profile.")
})
}
}
.tabItem {
Label("Home", systemImage: "list.bullet")
}