【问题标题】:SwiftUI: Center button text in ListSwiftUI:列表中的中心按钮文本
【发布时间】:2021-09-28 15:34:39
【问题描述】:

如果按钮位于列表中,是否可以将按钮文本居中?

struct HomeView: View {
    var body: some View {
        List {
            ForEach(["1", "2"], id: \.self) {
                Text("\($0)…").frame(maxWidth: .infinity, alignment: .center)
            }

            Button("Action button") {}
        }
    }
}

结果:

PS:

我试过这个:.frame(maxWidth: .infinity, alignment: .center) 但它不起作用

【问题讨论】:

    标签: swiftui watchkit watchos


    【解决方案1】:

    找到解决方案:

    Button{} 
    label: {
        Text("Action").frame(maxWidth: .infinity, alignment: .center)
    }
    

    【讨论】:

      【解决方案2】:

      使用嵌入在 GeometryReader 中的文本和 TapGesture。另外,为了使其更易于点击,请使用.contentShape(Rectangle())

      GeometryReader { metrics in
          List {
              ForEach(["1", "2"], id: \.self) { text in
                  Text("\(text)…").frame(width: metrics.size.width, alignment: .center)
                      .contentShape(Rectangle())
                      .onTapGesture {
                          print(text, "pressed")
                      }
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-27
        • 2012-06-14
        • 1970-01-01
        • 2020-07-14
        • 2023-04-07
        • 1970-01-01
        相关资源
        最近更新 更多