更改文本宽度而不增加堆栈宽度

问题描述 投票:0回答:3

enter image description here

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

它应该看起来像这样:

It should look like this

swift swiftui
3个回答
0
投票
不清楚您在这里问的是什么,但是您是否尝试过这样的事情:

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


0
投票
好的,那么这个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 } }) } } } }


0
投票
这里是基于对齐指南的可能方法。经过Xcode 11.4 / iOS 13.4的测试]

想法是在不同的图层上使用条形和文本,并使用自定义对齐指南对齐它们,并处理拐角处的情况以防止文本掉出屏幕。

demo

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

© www.soinside.com 2019 - 2024. All rights reserved.