【问题标题】:How can I make the full button clickable and not just the text? SwiftUI如何使整个按钮可点击而不仅仅是文本?斯威夫特用户界面
【发布时间】:2023-02-21 02:20:57
【问题描述】:
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
【解决方案1】:
这是一种方法,请务必阅读苹果文档,检查按钮和其他内容的不同初始化程序。
Button {
authenticateUser(username: username, password: password)
} label: {
Text("Login")
.foregroundColor(Color.black)
.frame(width: 300, height: 50)
.background(Color.blue)
.cornerRadius(10)
}
编码愉快!
【解决方案2】:
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)
}
}
}
【解决方案3】:
我发现执行此操作的最简单方法是将按钮代码作为 Button 初始值设定项的“action:”参数的参数,然后在按钮内设置 Button 的文本。
Button(action: { authenticateUser(username: username, password: password) }) {
Spacer()
Text(“Login”)
Spacer()
}.foregroundColor(Color.black)
.frame(width: 300, height: 50)
.background(Color.blue)
.cornerRadius(10)