SwiftUI 分段控件可定制
Posted
技术标签:
【中文标题】SwiftUI 分段控件可定制【英文标题】:SwiftUI Segmented Control Customizable 【发布时间】:2021-10-22 09:30:17 【问题描述】:我想在 SwiftUI 中实现这样的控件(https://github.com/Yalantis/Segmentio)(但没有图像):
最好的方法是什么? 我是否应该使用分段控件并对其进行自定义,例如中间的文本和底部边框?
或者我应该使用 ScrollView-->HStack-->XButtons? 这我已经尝试过了,但是我应该如何在选择更改时为底部边框设置动画? 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)
提前致谢。
更新:
在这里找到解决方案:
How to make view the size of another view in SwiftUI
【问题讨论】:
【参考方案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)
【讨论】:
以上是关于SwiftUI 分段控件可定制的主要内容,如果未能解决你的问题,请参考以下文章