【问题标题】:How can I fit a shape in swift ui to accommodate the length and width of a text view如何在 swift ui 中调整形状以适应文本视图的长度和宽度
【发布时间】:2020-04-19 23:51:14
【问题描述】:

ZStack{
                        RoundedRectangle(cornerRadius: 8).foregroundColor(.red).scaledToFit()//.frame(width: 200, height: 25)
                        HStack{
                            Image(systemName: "tag.fill").foregroundColor(.white)
                            Text("Tickets Not Available").font(.headline).foregroundColor(.white).fixedSize(horizontal: true, vertical: false)
                        }
                    }.scaledToFit()

如您所见,我的视图放置在 zstack 中,因此圆角矩形可以作为文本视图的背景。我已经尝试了很多不同的事情,比如将 .scaledtofit 放在哪里,它每次都会给我带来奇怪的结果。

【问题讨论】:

    标签: swift swiftui


    【解决方案1】:

    这是你所追求的(注意 Image.resizable):

    import SwiftUI
    
    struct ContentView: View {
    
    var body: some View {
        ZStack{
            RoundedRectangle(cornerRadius: 8).foregroundColor(.blue)
            HStack{
                Image(systemName: "tag.fill").resizable().padding(4).foregroundColor(.white).scaledToFit()
                Text("Get Tickets").font(.headline).foregroundColor(.white)
            }
        }.fixedSize()
    }
    

    【讨论】:

      【解决方案2】:

      这个问题有点不清楚,但是如果你想在文本视图中调整一个形状,并且你可以摆脱 scaledToFit,那么代码应该是:

      RoundedRectangle(cornerRadius: 8).foregroundColor(.red).frame(width: textView.width, height: textView.height)
      

      希望这会有所帮助,并希望您不需要使用 scaledToFit。 如果你确实在 cmets 中告诉我。

      【讨论】:

      • 我没有使用 swift ui,这不是我想要的,我希望矩形缩放到我所附图片中的文本大小。
      【解决方案3】:

      可重用的 ButtonStyle 在这里可能会有所帮助。而不是ZStack,使用.background 修饰符有助于保持按钮内容的大小:

      struct RoundedButtonStyle: ButtonStyle {
          func makeBody(configuration: Self.Configuration) -> some View {
              ZStack {
                  configuration.label
                      .font(.headline)
                      .padding()
                      .background(RoundedRectangle(cornerRadius: 8).foregroundColor(Color.blue))
              }
          }
      }
      

      使用示例:

      Button(
          action: {
              print("Button Tapped")
          },
          label: {
              HStack {
                  Image(systemName: "tag.fill")
                  Text("Tickets")
              }
          }
      )
      .buttonStyle(RoundedButtonStyle())
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多