【问题标题】:Can't seem to utilize Spacer() between text() and textfield()似乎无法在 text() 和 textfield() 之间使用 Spacer()
【发布时间】:2020-10-03 09:32:44
【问题描述】:

当我在 HStack 中并试图在我的 Text 和 Textfield 视图之间创建空间时,我似乎无法让 Spacer() 函数工作。 Spacer 用于分隔视图的其他区域,但每当我尝试在这两个元素之间分隔时,它都不起作用。

这是我正在使用的代码:

    VStack(alignment: .leading, spacing: 0) {
        Rectangle()
            .frame(height: 2, alignment: .top)
            .foregroundColor(Color("grey2"))
        Text("Tickets")
            .kerning(0.5)
            .scaledFont(name: "Gotham Medium", size: 18)
            .foregroundColor(Color("grey4"))
            .padding(.horizontal)
            .padding(.bottom, 3)
            .padding(.top, 35)
        Rectangle()
            .frame(height: 2, alignment: .top)
            .foregroundColor(Color("grey2"))

        HStack {
            Text("Ticket URL")
                .kerning(0.5)
                .scaledFont(name: "Gotham Book", size: 16)
                .foregroundColor(Color("spaceblack"))

            Spacer()

            TextField("Enter URL", text: $url)
        }
        .background(Color.blue)
        .padding()

        Rectangle()
            .frame(height: 2, alignment: .top)
            .foregroundColor(Color("grey2"))
    }
    .frame(maxWidth: .infinity)
    .background(Color.red)

【问题讨论】:

  • TextField 实际上与 Spacer 一样消耗所有可用宽度。那么你想达到什么目标呢?

标签: swiftui


【解决方案1】:

尝试将.fixedSize() 修饰符添加到您的TextField

   TextField("Enter URL", text: $url)
       .fixedSize()

或像这样设置frame

   TextField("Enter URL", text: $url)
       .frame(width:200, height:50, alignment:.leading)

问题是TextFieldSpacer() 会占用所有可用空间,在这种情况下TextField 获得优先权;但是,如果您为其指定固定大小或框架,则TextField 不会拉伸以占据全部空间,而是会被固定。

.fixedSize 将允许您的 TextField 从小处开始,但最终它将继续拉伸您编写的更多文本,这可能会导致不必要的行为。

.frame 会将您的尺寸固定为提供的宽度,因此不会有任何拉伸,Spacer 将优先占用可用空间。

【讨论】:

  • 成功了,谢谢。也非常感谢您的解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-10
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
相关资源
最近更新 更多