let months = ["january" , "februarry", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"]
var body: some View {
HStack {
ForEach(months, id: \.self) { month in
VStack {
if month == "october" {
Text(month)
}
Rectangle()
.frame(width: 25, height: 10)
}
}
}
}
我如何在不改变VStack宽度以及方格之间距离的情况下显示其全长文本。
它应该看起来像这样:
let months = ["january" , "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"]
var body: some View {
ScrollView (.horizontal, showsIndicators: false) {
HStack {
ForEach(months, id: \.self) { month in
VStack {
Text(month).fixedSize() // <--- this
Rectangle().frame(width: 25, height: 10)
}
}
}
}
}
let months = ["january" , "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"]
@State var chosenMonth = ""
var body: some View {
VStack {
HStack {
Spacer()
Text(chosenMonth)
Spacer()
}
HStack {
ForEach(self.months, id: \.self) { month in
Rectangle().frame(width: 25, height: 10).onAppear(perform: {
if month == "october" {
self.chosenMonth = month
}
})
}
}
}
}
想法是在不同的图层上使用条形和文本,并使用自定义对齐指南对齐它们,并处理拐角处的情况以防止文本掉出屏幕。
extension HorizontalAlignment {
private enum MonthAlignment : AlignmentID {
static func defaultValue(in d: ViewDimensions) -> CGFloat {
return d[HorizontalAlignment.center]
}
}
static let monthAlignment = HorizontalAlignment(MonthAlignment.self)
}
struct DemoMonthAlignment: View {
let months = ["january" , "februarry", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"]
@State private var selectedMonth = "october"
var body: some View {
VStack(alignment: .monthAlignment, spacing: 2) {
Text(selectedMonth)
.alignmentGuide(.monthAlignment, computeValue: { d in
if self.selectedMonth == self.months.first {
return d[.leading]
} else if self.selectedMonth == self.months.last {
return d[.trailing]
} else {
return d[HorizontalAlignment.center]
}
})
HStack {
ForEach(months, id: \.self) { month in
Group {
if month == self.selectedMonth {
Rectangle()
.foregroundColor(Color.red)
.alignmentGuide(.monthAlignment, computeValue: { d in
if month == self.months.first {
return d[.leading]
} else if month == self.months.last {
return d[.trailing]
} else {
return d[HorizontalAlignment.center]
}
})
} else {
Rectangle()
}
}
.frame(width: 25, height: 10)
}
}
}
}
}