๐example โฉ Picker
Last updated
Last updated
import SwiftUI
import PlaygroundSupport
// ๐ RoundedRectangle(), ๐ shape.outlined()
let r1 = RoundedRectangle().outlined(fill: .blue)
let r2 = RoundedRectangle().outlined(fill: .pink)
let spring = Animation.spring(response: 0.5, dampingFraction: 0.5, blendDuration: 0)
// live view
struct ContentView: View {
// โญ๏ธ view state
@State private var index = 0
@State private var change = false
var a: Double { change ? 1 : 0 } // opacity
// helper
func makeBody(size: CGSize) -> some View {
let w = size.width
var isTag0 : Bool { index == 0 }
var d : CGFloat { isTag0 ? 0 : w } // offset
var t : Double { isTag0 ? 1 : 0 } // opacity
return ZStack {
r1
.offset(x: d).opacity(t) // slide & fade away
.animation(spring)
r2
.offset(x: d - w).opacity(1 - t)
.animation(.default)
}
}
// view body
var body: some View {
VStack {
if self.change {
// rounded rects
GeometryReader { geo in
self.makeBody(size: geo.size)
}.transition(.asymmetric(insertion: .move(edge: .bottom), removal: .opacity))
// segmented control (picker)
Picker("Day & Night", selection: $index) {
Text("๐ Day").tag(0)
Text("๐ Night").tag(1)
}.pickerStyle(SegmentedPickerStyle())
} else {
// segmented control (picker)
Picker("Day & Night", selection: $index) {
Text("๐ Day").tag(0)
Text("๐ Night").tag(1)
}.pickerStyle(SegmentedPickerStyle())
// rounded rects
GeometryReader { geo in
self.makeBody(size: geo.size)
}.transition(.asymmetric(insertion: .move(edge: .top), removal: .opacity))
}
Divider().padding(.top, 4)
Button(action: { self.change.toggle() }, label: {
Text("Change")
.font(.caption)
.padding(8)
.padding(.horizontal, 6)
.accentColor(.white)
.background(Color.orange)
.cornerRadius(10)
})
}// container: VStack
.frame(350, 200)
.shadow(radius: 8)
.padding()
.background(Color.gray)
.cornerRadius(10).animation(.default)
}
}
PlaygroundPage.current.setLiveView(ContentView())
SwiftUI โฉ Views and Controls โฉ Picker
SwiftUI Custom PickerStyle - StackOverflow