私は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")
}
}
}
}}
}
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加