我正在使用SwiftUI编写一个应用程序,并使用Picker来呈现用户选择的选项列表。
当有人点击Picker并查看选项时,我想添加一些页脚文本来解释列表中的选择。以下是我想要实现的示例截图,取自iOS设置应用程序:
如何使用SwiftUI实现这一点?
我在主屏幕上包含Picker的Section中定义了页脚(“这是设置的简短描述。”),这很好用,但是类似的代码却没有在显示Picker选项的屏幕上添加页脚。
这是我的示例代码:
import SwiftUI
class ViewModel: ObservableObject {
enum Option: String, Identifiable, CaseIterable, CustomStringConvertible {
case optionOne
case optionTwo
case optionThree
var id: Option {
self
}
var description: String {
rawValue.prefix(1).uppercased() + rawValue.dropFirst()
}
}
@Published var selectedOption: Option = .optionOne {
didSet {
print("new option selected: \(selectedOption.description)")
}
}
}
struct ContentView: View {
@ObservedObject var viewModel = ViewModel()
var body: some View {
NavigationView {
Form {
Section(footer: Text("Here is a short description of the setting.")) {
Picker(selection: $viewModel.selectedOption,
label: Text("Choice")) {
Section(footer: Text("This is some additional text to help the user understand the options.")) {
ForEach(ViewModel.Option.allCases) { type in
Text(type.description)
}
}
}
}
}.navigationBarTitle(Text("Main Screen"))
}
}
}
还有,当这个列表加载时,我看到了一个奇怪的跳动。我该如何避免这种情况?
foregroundColor(.secondary)
将当前选择添加到了NavigationLink
的右侧,并将Button
的foregroundColor
更改为.primary
。 - gohnjanotis