我正在尝试弄清楚如何检索此HStack
的大小以自动计算将帧分为3个。该计划是在活动屏幕标题下方设置一个彩色条,请参见下面的图片示例。
VStack{
HStack{
Text("Overview").fontWeight(.black)
Spacer()
Text("Bio").fontWeight(.black)
Spacer()
Text("Location").fontWeight(.black)
}
}
我的最终目标是实现这一目标。
答案 0 :(得分:0)
将HStack包裹在GeometryReader
GeometryReader { g in
HStack {
Text("Overview").frame(width: g.size.width / 3)
Text("Bio").frame(width: g.size.width / 3)
Text("Location").frame(width: g.size.width / 3)
}
}
https://developer.apple.com/documentation/swiftui/geometryreader
答案 1 :(得分:0)
这个怎么样:
HStack{
Spacer().overlay(Text("OverView").bold())
Spacer().overlay(Text("Bio").bold())
Spacer().overlay(Text("Location").bold())
}
答案 2 :(得分:0)
尝试下面的代码
ContentView
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
}
}
}
LineView
struct LineView: View {
var body: some View {
VStack {
EmptyView()
}
}
}
TextView
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
}
}
}
输出: