'SwiftUI Segmented Control Customizable
I want to achieve such a control like this (https://github.com/Yalantis/Segmentio) in SwiftUI (but without image):
What would be the best approach?
Should I use a segmented control and customize it, like text in the middle and a bottom border?
Or should I use a ScrollView-->HStack-->XButtons?
This I already tried, but how should i animate the bottom border on selection change? Is something possible in SwiftUI?
ScrollView(.horizontal) {
HStack(alignment: .center, spacing: 8, content: {
Button(action: {
print("Button pressed")
}, label: {
Text("Example Button")
.padding(20)
})
... button 2, ... button 3 and so on
}).frame(height: 80, alignment: .leading)
}
Solution 1:[1]
struct MyTestView2: View {
struct Disasterd: Identifiable {
var id: Int
var systemImage: String
var text: String
}
@State var disasters = [Disasterd(id: 1, systemImage: "wind", text: "wind"),
Disasterd(id: 2, systemImage: "sun.max", text: "sun"),
Disasterd(id: 3, systemImage: "cloud.rain", text: "rain")]
@State var selected = 0
var body: some View {
VStack {
Text("with image")
ScrollView(.horizontal) {
HStack(alignment: .center, spacing: 8, content: {
ForEach(disasters, id:\.id) { dis in
Button(action: {
print("Button pressed")
selected = dis.id
}, label: {
VStack {
Image(systemName: dis.systemImage)
.font(.system(size: 40))
.frame(width: 80, height: 50)
Text(dis.text)
.padding(.top,20)
Rectangle()
.frame(width: 80, height: 5)
.foregroundColor(selected == dis.id ? .orange:.white)
}
})
}
})
.animation(.default)
.frame(height: 180, alignment: .leading)
}
Text("without image")
ScrollView(.horizontal) {
HStack(alignment: .center, spacing: 8, content: {
ForEach(disasters, id:\.id) { dis in
Button(action: {
print("Button pressed")
selected = dis.id
}, label: {
VStack {
Text(dis.text)
.frame(width: 80, height: 20)
.padding(.top,20)
Rectangle()
.frame(width: 80, height: 5)
.foregroundColor(selected == dis.id ? .orange:.white)
}
})
}
})
.animation(.default)
.frame(height: 180, alignment: .leading)
}
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Simone Pistecchia |