Smu*_*aco 5 ios swift swift5 ios13 swiftui
struct ContentView : View {
var body: some View {
NavigationView {
TabbedView {
PasswordGenerator()
.tabItemLabel {
Image("KeyGlyph")
Text("Generator")
}
PasswordGeneratorSettings()
.tabItemLabel {
Image("SettingsGlyph")
Text("Settings")
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
它不会编译,但已在WWDC的Swift Essentials视频中使用(请参阅第54:30分钟),我已经看到了一些变通方法,例如VStack变通方法(但即使有很多缺陷,左侧选项卡也离它太远了左右选项卡距离右侧太远,切换选项卡时,只有第一个最初加载的选项卡会加载,而另一个选项卡则保持空白,使用标签无济于事。那么,如何有两个用于加载视图并具有图像和文本的选项卡?
Mak*_*aki 12
使用 XCode beta 3,以下内容应该可以工作:
import SwiftUI
struct Home : View {
@State private var currentTab = 1
var body: some View {
TabbedView(selection: $currentTab) {
FirstView()
.tabItem {
VStack {
Image(systemName: "1.circle")
Text("First Tab")
}
}.tag(1)
SecondView()
.tabItem {
VStack {
Image(systemName: "2.circle")
Text("Second Tab")
}
}.tag(2)
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,将选项卡标签包含在 a 中VStack似乎是可选的。所以,你可能决定放弃这个,比如:
import SwiftUI
struct Home : View {
@State private var currentTab = 1
var body: some View {
TabbedView(selection: $currentTab) {
FirstView()
.tabItem {
Image(systemName: "1.circle")
Text("First Tab")
}.tag(1)
SecondView()
.tabItem {
Image(systemName: "2.circle")
Text("Second Tab")
}.tag(2)
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 9
对于那些仍在寻找如何执行此操作的人,这里是 Xcode 11 GM 的更新。
struct Tabs: View {
@State private var selected = 0
var body: some View {
TabView(selection: $selected) {
MyFirstView()
.tabItem {
Image(systemName: (selected == 0 ? "star.fill" : "star"))
Text("One")
}.tag(0)
MySecondView()
.tabItem {
Image(systemName: (selected == 1 ? "star.fill" : "star"))
Text("Two")
}.tag(1)
MyThirdView()
.tabItem {
Image(systemName: (selected == 2 ? "star.fill" : "star"))
Text("Three")
}.tag(2)
}
.edgesIgnoringSafeArea(.all) // Important if you want NavigationViews to go under the status bar...
}
}
Run Code Online (Sandbox Code Playgroud)
TabbedView()已被弃用TabView()。
使用整数来选择视图对我来说很糟糕,从我使用tag()UIButton 和 UIView 的日子开始,最好枚举你正在做的事情,而不是分配一个范围很大的硬编码值。即Int.min()到Int.max()。这也使代码在未来更易于阅读和维护。
TabView(selection: ) 可用于选择索引,并声明为:
public struct TabView<SelectionValue, Content> : View where SelectionValue : Hashable, Content : View {
public init(selection: Binding<SelectionValue>?, @ViewBuilder content: () -> Content)
…
Run Code Online (Sandbox Code Playgroud)
这意味着您可以选择具有任何可散列内容的索引。
我们可以使用一个enum符合来Hashable包含选项卡列表的方式,这样以后可以使用一个 Observable 来帮助控制和加载视图的状态。或者将枚举作为应用程序状态的一部分。我相信您可以使用大量资源来找到满足您需求的合适解决方案。
struct MainTabView: View {
@State private var selection: Tabs = .profile
private enum Tabs: Hashable {
case content
case profile
}
var body: some View {
TabView(selection: $selection) {
// Learn Content
Text("The First Tab")
.tabItem {
Image(systemName: "book")
Text("Learn")
}.tag(Tabs.content)
// The Users Profile View.
ProfileView()
.tabItem {
Image(systemName: "person.circle")
Text("Profile")
}.tag(Tabs.profile)
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3057 次 |
| 最近记录: |