はじめに
デフォルトで用意されているコードスニペットを見ていたら使ったことのない機能を見つけたので使ってみました。
サンプルアプリ
実装
import SwiftUI
struct ContentView: View {
@State private var sectionOptions: SectionOptions = .none
var body: some View {
List {
Section {
Text("コンテンツ")
} header: {
if sectionOptions.contains(.showHeader) {
Text("ヘッダー")
}
} footer: {
if sectionOptions.contains(.showFooter) {
Text("フッター")
}
}
Button {
sectionOptions = .none
} label: {
Text("none")
}
.disabled(sectionOptions == .none)
Button {
sectionOptions = .headerOnly
} label: {
Text("headerOnly")
}
.disabled(sectionOptions == .headerOnly)
Button {
sectionOptions = .footerOnly
} label: {
Text("footerOnly")
}
.disabled(sectionOptions == .footerOnly)
Button {
sectionOptions = .headerAndFooter
} label: {
Text("headerAndFooter")
}
.disabled(sectionOptions == .headerAndFooter)
}
}
}
struct SectionOptions: OptionSet {
let rawValue: Int
static let showHeader = SectionOptions(rawValue: 1 << 0)
static let showFooter = SectionOptions(rawValue: 1 << 1)
static let none: Self = []
static let headerOnly: Self = [.showHeader]
static let footerOnly: Self = [.showFooter]
static let headerAndFooter: Self = [.showHeader, .showFooter]
}
おわり
複数の状態を1つの値で持っておけるのは便利ですね
公式ドキュメント