SwiftUI TextField 取最大宽度

SwiftUI TextField takes max width

我有一个导航列表,每个列表项都采用这种格式:

HStack {
        TextField("Insert something here.",text: self.$userData.pages[i].title)
            .border(Color.blue)
        Spacer()
    }

结果如下:

The touchable area is highlighted by the blue border and it takes the whole width of the row

问题在于,尽管列表项是一个导航 link,但用户单击该项目的任意位置将导致他们编辑文本内容。我更喜欢 TextFieldText:

具有相同的宽度

The blue border wraps the text instead of taking the max width

因此,如果用户在 TextField 之外单击,导航会正常工作,但如果他们在 上单击 文本,它将允许他们编辑文本。 (以上视图带有 Text 字段)。

如果我问了一个不清楚或不好的问题,我深表歉意。我是 Stack Overflow 和 SwiftUI 的新手。

编辑:

我试过使用 fixedSize 修饰符,TextField 正确地包装了我的文本,但现在导航 Link 不起作用(即点击它无法导航) .这是我的完整代码:

NavigationLink(destination: PageView(page: self.userData.pages[i])) {
                        HStack {
                            Button(action: {}){
                                TextField(" ", text: self.$userData.pages[i].title)
                                .fixedSize()

                            }
                            .buttonStyle(MyButtonStyle())
                            .border(Color.blue)
                            Spacer()
                        }
                    }

不用道歉,你的问题很明确。 您可以使用 fixedSize()

所以你的代码应该是这样的

HStack {
        TextField("Insert something here.",text: self.$userData.pages[i].title)
            .border(Color.blue)
            .fixedSize()
        Spacer()
    }

您可以通过像这样传递参数来进一步指定您希望如何拉伸,verticalhorizontal 甚至两者 .fixedSize(horizontal: true, vertical: false)

已更新答案以满足您的新要求

import SwiftUI

struct Whosebug5: View {
    @State var text: String = ""
    @State var selection: Int? = nil

    var body: some View {
        NavigationView {
            ZStack {
                NavigationLink(destination: Page2(), tag: 1, selection:self.$selection) {
                    Color.clear
                        .onTapGesture {
                            self.selection = 1
                        }
                }


                TextField("Text", text: self.$text)
                    .fixedSize()
            }
        }
    }
}

struct Whosebug5_Previews: PreviewProvider {
    static var previews: some View {
        Whosebug5()
    }
}

struct Page2: View {
    var body: some View {
        Text("Page2")
    }
}

我们在这里使用了 ZStack 来分隔我们的 TextField 和我们的 NavigationLink 以便它们可以单独交互。

请注意在我们的 TextField 之前使用 Color.clear,这是故意的,以便我们的 TextField 具有交互优先级。我们还使用了 Color.clear 因为它会作为背景拉伸并且它是 clear 所以它不可见。

显然我在这里硬编码了 1 但这可以来自 ListForEach

此外,如果您不想使用 selectiontag,您可以这样做

...
@State var isActive: Bool = false
...
NavigationLink(destination: Page2(), isActive: self.$isActive) {
     Color.clear
          .onTapGesture {
               self.isActive.toggle()
          }
}
....