我正在 SwiftUI 上编写一个应用程序,我使用 Picker 显示一个选项列表供用户选择。
当有人点击选择器并看到选项时,我想添加一些页脚文本来解释列表中的选项。
这是我想要完成的示例屏幕截图,取自 iOS 设置应用程序:
如何使用 SwiftUI 实现这一目标?
我在主屏幕上为包含选择器的部分定义了一个页脚(“这是设置的简短描述。”)并且工作正常,但类似的代码不会在屏幕上添加显示选择器选项的页脚。
这是我的示例代码:
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"))
}
}
}
此外,当这个列表加载时,我看到了一个奇怪的跳跃。我怎样才能避免这种情况?
最佳答案
您可能不需要另一个双页脚,也许只是一个提示标题
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")) {
ForEach(ViewModel.Option.allCases) { type in
Text(type.description)
}.navigationBarTitle("hint title here", displayMode: .inline)
}
}.navigationBarTitle("Main Screen", displayMode: .inline)
}.navigationBarTitle(Text("Main Screen"))
}
}
}
没有选择器,您可以构建自己的选项列表:struct ContentView: View {
@ObservedObject var viewModel = ViewModel()
var body: some View {
NavigationView {
Form {
Section(footer: Text("Here is a short description of the setting.")) {
NavigationLink(destination: SelectionItemView(selection: $viewModel.selectedOption)) {
Text("Choice")
}
}.navigationBarTitle("Main Screen", displayMode: .inline)
}.navigationBarTitle(Text("Main Screen"))
}
}
}
struct SelectionItemView: View {
@Binding var selection: ViewModel.Option
var body: some View{
Form{
Section(footer: Text("Here is a detailed description of the setting.")) {
ForEach(0 ..< ViewModel.Option.allCases.count, id: \.self) { index in
HStack{
Button(action: {
self.selection = ViewModel.Option.allCases[index]
}){Text(ViewModel.Option.allCases[index].description)}
Spacer()
if ( self.selection == ViewModel.Option.allCases[index] ){
Image(systemName: "checkmark")
}
}
}
}}
}
}
关于ios - 如何在 SwiftUI Picker 选项下方添加节页脚文本?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59832873/