如何使整个按钮可点击而不仅仅是文本? SwiftUI

问题描述 投票:0回答:3
                    Button("Login") {
                        authenticateUser(username: username, password: password)
                    }
                    .foregroundColor(Color.black)
                    .frame(width: 300, height: 50)
                    .background(Color.blue)
                    .cornerRadius(10)
                    
                    NavigationLink(destination: HomeView(), isActive: $showingLoginScreen) {
                        EmptyView()
                        
                    }

我是编码新手,不知道如何解决这个问题。我必须单击文本才能激活按钮。

ios swift button text swiftui
3个回答
0
投票

这是一种方式,一定要阅读苹果文档,检查按钮和其他东西的不同初始化程序。

Button {
  authenticateUser(username: username, password: password)
} label: {
  Text("Login")
      .foregroundColor(Color.black)
      .frame(width: 300, height: 50)
      .background(Color.blue)
      .cornerRadius(10)
}

快乐的编码!


0
投票
struct ContentView: View {
    @State private var isTapped = false

    var body: some View {
        Button {
            isTapped.toggle()
        } label: {
            Text("Login")
                .foregroundColor(Color.black)
                .frame(width: 300, height: 50)
                .background(isTapped ? Color.blue : Color.green)
                .cornerRadius(10)
        }
    }
}

0
投票

我发现最简单的方法是将按钮的代码作为 Button 初始值设定项的“action:”参数的参数,然后在按钮内设置 Button 的文本。然后使用框架修改器使按钮成为您想要的大小。文本周围的 Spacers() 对于使按钮扩展以填充框架并使整个区域可点击很重要。

Button(action: { authenticateUser(username: username, password: password) }) {
        Spacer()
        Text(“Login”)
        Spacer()                   
 }.foregroundColor(Color.black)
      .frame(width: 300, height: 50)
      .background(Color.blue)
      .cornerRadius(10)
© www.soinside.com 2019 - 2024. All rights reserved.