首页 > 解决方案 > 在不增加堆栈宽度的情况下更改文本宽度

问题描述

在此处输入图像描述

  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 的宽度以及方块之间的距离的情况下以全长显示文本。

它应该如下所示:

它应该看起来像这样

标签: swiftswiftui

解决方案


好的,那么这个 hack 怎么样:

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
                    }
                })
            }
        }
    }
}

推荐阅读