首页 > 解决方案 > 无法输入文本字段

问题描述

我正在SignUp使用 SwiftUI 框架创建一个屏幕。

我有两个文本字段,FirstNameLastName,和一个按钮。

我将它们分组在一个VStack.

当我运行应用程序时,该按钮是可点击的,但我无法在文本字段中输入任何内容。

这是我的代码:

@State var firstName = ""
@State var lastName = ""
var body: some View {

    NavigationView {

        VStack {

            VStack {

                VStack {

                    Group {
                       TextField($firstName, placeholder: Text("First Name")).padding(10)
                    }.background(Color.white).clipShape(RoundedRectangle(cornerRadius: 5))
                        .shadow(radius: 3)

                    Group {
                        TextField($lastName, placeholder: Text("Last Name")).padding(10)
                    }.background(Color.white).clipShape(RoundedRectangle(cornerRadius: 5))
                        .shadow(radius: 3)

                    Button(action: {
                    }) {
                        Group {
                            Text("Create User").color(.white).padding(10)
                        }.background(Color.blue).clipShape(RoundedRectangle(cornerRadius: 5))
                            .shadow(radius: 5)
                    }
                }.padding(12)
                .background(Color.gray)
                .shadow(radius: 5)

            }.background(Color.gray)

        }.navigationBarTitle(Text("Sign Up"))
    }
}

标签: iosswiftuser-interfacetextfieldswiftui

解决方案


在这种特定情况下,似乎shadow在颜色/不透明度效果之后设置会导致问题。

为了确保合成效果在阴影之前.compositingGroup()渲染,您可以添加到您的VStack- 就在之前shadow- 这可以解决问题。

文档说:

合成组使此视图的祖先视图中的合成效果(如不透明度和混合模式)在此视图渲染之前生效。

修改后的代码

VStack {
    // [...]  
}
.padding(12)
.background(Color.gray)
.compositingGroup() // THIS
.shadow(radius: 5)
.navigationBarTitle(Text("Sign Up"))

UI 可以通过这种方式进一步简化 - 它达到了相同的结果。

struct ContentView: View {

    @State var firstName = ""
    @State var lastName = ""

    var body: some View {

        NavigationView {

            VStack {

                    TextField($firstName, placeholder: Text("First Name"))
                        .padding(10)
                        .background(Color.white)
                        .cornerRadius(5)
                        .shadow(radius: 3)

                    TextField($lastName, placeholder: Text("Last Name"))
                        .padding(10)
                        .background(Color.white)
                        .cornerRadius(5)
                        .shadow(radius: 3)

                    Button(action: { }) {
                        Text("Create User")
                            .color(.white)
                            .padding(10)
                            .background(Color.blue)
                            .cornerRadius(5)
                            .shadow(radius: 5)
                    }
            }
            .padding(12)
            .background(Color.gray)
            .compositingGroup()
            .shadow(radius: 5)
            .navigationBarTitle(Text("Sign Up"))
        }

    }

}

推荐阅读