gpt4 book ai didi

SwiftUI 使按钮在 HStack 中水平地彼此靠近

转载 作者:行者123 更新时间:2023-12-04 14:47:08 27 4
gpt4 key购买 nike

我试图让键盘上的按钮在水平方向上彼此靠得更近。首先我尝试调整按钮框架的宽度。但是我发现,如果我减小框架宽度,一些像“W”这样的长宽字符将无法正确显示。

enter image description here

然后我尝试将 HStack 的间距设置为负数,就像我在下面的代码中所做的那样。

enter image description here

但这会导致按钮相互重叠,可点击区域向左移动,这是 Not Acceptable (可以通过设置背景颜色为蓝色来检查)。

enter image description here

有没有办法在不改变字体大小的情况下减小按钮距离?

struct KeyboardView: View {

let KeyboardStack = [["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P"],
["A", "S", "D", "F", "G", "H", "J", "K", "L"],
["Z", "X", "C", "V", "B", "N", "M"]]

var body: some View {
VStack(spacing: 9) {
ForEach(KeyboardStack.indices) { row in
let num = KeyboardStack[row].indices
HStack(spacing: -12) {
ForEach(num) { column in
Button(KeyboardStack[row][column]) {}
.frame(width: 12, height: 12,alignment: .center)
.padding()
// .background(Color.blue)
.font(.system(size: 15, weight: .regular, design: .default))
.foregroundColor(.white)
.buttonStyle(PlainButtonStyle())
}
}
.frame(width: 255, height: 19.5, alignment:.center)
}
}
.frame(width: 445, height: 60, alignment:.center)
}
}

最佳答案

要做的第一件简单的事情就是去掉你的 padding() 修饰符,它会为每个按钮添加额外的填充。

我假设,鉴于这是一个键盘 View ,您希望所有键的宽度都相同。您可以使用 PreferenceKey 来存储适合特定字母所需的最大宽度,然后将其用于每个 Button,使其仅根据需要变大:

struct KeyboardView: View {
@State private var keyWidth : CGFloat = 0

let KeyboardStack = [["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P"],
["A", "S", "D", "F", "G", "H", "J", "K", "L"],
["Z", "X", "C", "V", "B", "N", "M"]]

var body: some View {
VStack(spacing: 9) {
ForEach(KeyboardStack.indices) { row in
let num = KeyboardStack[row].indices
HStack(spacing: 0) {
ForEach(num) { column in
Button(action: {}) {
Text(KeyboardStack[row][column])
.font(.system(size: 15, weight: .regular, design: .default))
.foregroundColor(.white)
.buttonStyle(PlainButtonStyle())
.frame(width: keyWidth)
.background(GeometryReader {
Color.clear.preference(key: KeyWidthKey.self,
value: $0.frame(in: .local).size.height)
})
.contentShape(Rectangle())
}
}
}.onPreferenceChange(KeyWidthKey.self) { keyWidth = $0 }

}
}
}
}

struct KeyWidthKey: PreferenceKey {
static var defaultValue: CGFloat { 0 }
static func reduce(value: inout Value, nextValue: () -> Value) {
value = max(value, nextValue())
}
}

请注意,如果您更改字体大小,此解决方案将继续有效,因为它不依赖于每个键的硬编码 frame 大小。

enter image description here

关于SwiftUI 使按钮在 HStack 中水平地彼此靠近,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69830940/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com