试试下面的代码
内容视图
struct ContentView: View {
@State var linePlaceType : LinePlace = .leading
var selectedColor : Color = .purple
var defaultColor : Color = .gray
var body: some View {
GeometryReader { g in
VStack {
HStack {
Button(action: {
self.linePlaceType = .leading
}) {
TextView(text: "Overview", textColor: self.getColorForText(.leading)).frame(width: g.size.width / 3)
}
Button(action: {
self.linePlaceType = .center
}) {
TextView(text: "Bio", textColor: self.getColorForText(.center)).frame(width: g.size.width / 3)
}
Button(action: {
self.linePlaceType = .trailing
}) {
TextView(text: "Location", textColor: self.getColorForText(.trailing)).frame(width: g.size.width / 3)
}
}.frame(height: 40)
.background(self.defaultColor.opacity(0.2))
ZStack(alignment: self.linePlaceType.alignment) {
LineView().frame(width: g.size.width, height: 5).background(self.defaultColor)
LineView().frame(width: g.size.width / 3, height: 5).background(self.selectedColor)
}.offset(x: 0, y: -12)
}
}
}
func getColorForText(_ linePlaceType: LinePlace) -> Color {
if (linePlaceType == self.linePlaceType) {
return self.selectedColor
}
else {
return self.defaultColor
}
}
}
线视图
struct LineView: View {
var body: some View {
VStack {
EmptyView()
}
}
}
文本视图
struct TextView: View {
let text : String?
let textColor: Color?
var body: some View {
VStack {
Text(self.text!)
.font(.headline)
.foregroundColor(self.textColor!)
}
}
}
枚举 : LinePlace
enum LinePlace {
case leading
case center
case trailing
}
extension LinePlace {
var alignment: Alignment {
switch self {
case .leading:
return .leading
case .center:
return .center
case .trailing:
return .trailing
}
}
}
输出: