ios - SwiftUI 中的按钮大小和颜色
问题描述
我是 SwiftUI 和 iOS 开发的新手。
我尝试创建 2 个按钮,但无法更改背景颜色或大小。
它看起来像这样:
下面是代码:
HStack {
Button( action: {
print("click")
}){
Text("Login")
.foregroundColor(.purple)
.padding()
.overlay(
RoundedRectangle(cornerRadius: 20)
.stroke(Color.purple, lineWidth: 1)
)
}
Button( action: {
print("click")
}){
Text("Register")
.foregroundColor(.white)
.padding()
.overlay(
RoundedRectangle(cornerRadius: 20)
.stroke(Color.black, lineWidth: 1)
)
}
}
我正在寻找一个按钮,它几乎使用了屏幕的一半,每边的边距为 10px。目标是让 2 个按钮几乎覆盖显示屏的宽度。我也试着让它更薄。上下边框之间的距离太大,当左右边框必须更宽时,我希望它靠近文本。
我也不知道如何将按钮背景颜色更改为黑色
任何想法 ?
谢谢
解决方案
您可以创建自己的ButtonStyle
,您可以完全自定义和重用:
struct CustomButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.padding(10) // *make it thinner*
.frame(maxWidth: .infinity) // expand horizontally
.foregroundColor(.purple)
.background(
Rectangle()
.stroke(Color.purple, lineWidth: 1)
.background(Color.black) // *change the button background color to black*
.cornerRadius(20)
)
.padding(.horizontal, 10) // *margin of 10px on each side*
.opacity(configuration.isPressed ? 0.7 : 1)
}
}
struct ContentView: View {
var body: some View {
HStack {
Button("Login") {
print("click")
}
.buttonStyle(CustomButtonStyle())
Button("Register") {
print("click")
}
.buttonStyle(CustomButtonStyle())
}
}
}
推荐阅读
- vim - 如何在文档的最开头启动 Vim 语法区域,同时在同一位置允许关键字匹配?
- postgresql - 在 postgresql 中喜欢和不喜欢
- python - PyQt5 突出显示选定的 TreeWidget 单元格
- arrays - 获取 json 对象数组并映射到模型类 Laravel
- python - 如何使用 Python 将注册表单连接到 MySQL?
- node.js - express 是怎么知道这个路由的?
- python - execute和execute_script selenium函数python有什么区别
- docker - 在 golang 中导入存档/tar 时 docker run 失败
- applescript - Applescript选择滚动区域中的所有复选框
- java - 当一个项目依赖于其他项目时如何使用gradle构建jar