【问题标题】:swiftui textfiled and button inside a buttonswiftui 文本字段和按钮内的按钮
【发布时间】:2020-01-19 05:16:53
【问题描述】:

当用户单击视图的背景区域时,我试图触发按钮。 作为一种解决方案,我决定制作一个按钮并将视图作为标签放入按钮中。 但问题是按钮即使在 TextField 上也会触发,有时也会在内部的另一个按钮上触发。

如何禁用我选择的某些视图(在这种情况下为 TextField 和 Button)上的后退按钮?

我在下面附上我的代码和rendered preview

import SwiftUI

struct ButtonOnbutton: View {
    @State var memo: String = ""
    var body: some View {
        Button(action: {
            print("down button clicked")
        }) {
            VStack(spacing: 10) {
                Text("before")
                    .foregroundColor(.white)
                TextField("type memo", text: $memo)
                    .font(.custom("SFProDisplay-Regular", size: 12))
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                Text("after")
                    .foregroundColor(.white)
                Button(action: {
                    print("inside button clicked")
                }) {
                    Text("inside button")
                        .foregroundColor(.white)
                }
                .background(Color.red)
            }
        }
        .background(Color.blue)
    .padding()
    }
}

struct buttonOnbutton_Previews: PreviewProvider {
    static var previews: some View {
        ButtonOnbutton()
    }
}

【问题讨论】:

    标签: swift swiftui ios13 xcode11 swift5


    【解决方案1】:

    如果我正确理解您的目标,那么最好使用onTapGesture 而不是按钮,如下所示

    var body: some View {
        VStack(spacing: 10) {
            Text("before")
                .foregroundColor(.white)
            TextField("type memo", text: $memo)
                .font(.custom("SFProDisplay-Regular", size: 12))
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .onTapGesture {} // << just blocks outer tap
            Text("after")
                .foregroundColor(.white)
            Button(action: {
                print("inside button clicked")
            }) {
                Text("inside button")
                    .foregroundColor(.white)
            }
            .background(Color.red)
        }
        .background(Color.blue)
        .onTapGesture {
            print("background area clicked")
        }
        .padding()
    }
    

    【讨论】:

    • 我想不出在 textField 上添加 tapGesture 的想法。我解决了这个问题。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-21
    • 1970-01-01
    • 2021-12-02
    • 2013-12-23
    相关资源
    最近更新 更多