gpt4 book ai didi

swiftui - 有没有办法在自定义 SwiftUI ButtonStyle 中设置字体跟踪(即间距)?

转载 作者:行者123 更新时间:2023-12-05 02:34:43 25 4
gpt4 key购买 nike

在 SwiftUI 中,您可以使用 tracking View modifier 在 Text View 上设置字体跟踪(字母间距):

Text("Hello, World!")
.tracking(10)

如果您有一个 Button 并应用您的自定义 ButtonStyle,您可以对按钮的样式进行各种修改,但是由于 configuration.label 不是 Text 的实例,而是 ButtonStyleConfiguration.Label 的实例,我无法直接访问应用 tracking。有没有一种方法可以做到这一点而不必直接在 Buttonlabel View 上设置它?这似乎是您应该能够做的事情,因为它是与样式相关的事情,但我不知道如何完成它。

public struct MyStyle: ButtonStyle {
public func makeBody(configuration: Configuration) -> some View {
configuration.label
// (if I tried to put `.tracking` here it wouldn't work because it isn't Text)
.foregroundColor(Color.red)
.clipShape(Capsule())
// … etc.
}
}

ViewModifier to change both font and tracking看起来~相关但没有相关答案。

最佳答案

是的,ButtonStyleConfiguration.LabelText 不匹配,但您可以忽略标准标签,并通过接口(interface)契约(Contract)请求自己的样式,这正是您需要的(在本例中为 Text),如下面的演示

public struct MyStyle: ButtonStyle {
let label: Text // << here !!

public func makeBody(configuration: Configuration) -> some View {
label // << here !!
.tracking(10)
.foregroundColor(configuration.isPressed ? .black : .red)
.clipShape(Capsule())
}
}

并将其用作(或使用按钮构建器创建自己的按钮扩展以隐藏那些不需要的 curl )

Button(action: {
// action here
}){}
.buttonStyle(MyStyle(label: Text("Hello")))

使用 Xcode 13.2/iOS 15.2 测试

enter image description here

关于swiftui - 有没有办法在自定义 SwiftUI ButtonStyle 中设置字体跟踪(即间距)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70715341/

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