如果我已经有一个按钮,其字体大小由.font()修饰符定义,如下所示:

Button("Hello"){}
    .font(.system(size: 10))

我如何使用ButtonStyle.buttonStyle()来决定这个按钮的大小?

struct CustomButtonStyle: ButtonStyle {
    
    func makeBody(configuration: Configuration) -> some View {
        let size = 2 * configuration.label.fontSize       // Something like this
        
        configuration.label
            .frame(width: size, height: size)
            .background(.red)
    }
    
}

或者这种方法还有其他 Select 吗?我试着直接使用.padding().但它不能正常工作.正如您在上面的屏幕截图中所看到的,由于SF符号的大小不同,因此生成了不同的大小.

func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .padding()
            .background(.red)
    }

enter image description here

推荐答案

SwiftUI允许创建字体,但不允许读取字体属性,因此您必须将其存储在某个模型层(例如UIFont)并从外部注入.或者根本不要使用它,而是使用一些动态的东西,如填充等,因为文本/标签会自动将字体大小调整为帧大小.

我的意思是:

private let uiFont = UIFont.preferredFont(forTextStyle: .title1)
private var font: Font { Font(uiFont as CTFont) }

var body: some View {
    HStack {
        Button(action: {}) {
            Image(systemName: "star")
        }

        Button(action: {}) {
            Image(systemName: "bolt.horizontal")
        }
    }
    .buttonStyle(CustomButtonStyle(font: uiFont)) // << !!
    .font(font)                                   // << !!

和风格

struct CustomButtonStyle: ButtonStyle {
    var font = UIFont.preferredFont(forTextStyle: .body)  // << default !!

    func makeBody(configuration: Configuration) -> some View {
        let size = font.lineHeight * 2.0 // << can use any param and/or factor !!
        configuration.label
            .frame(width: size, height: size)
            .background(.red)
    }
}

这给出了(Xcode 13.4/iOS 15.5):

demo

Test code on GitHub

Swift相关问答推荐

如何在一个角色隔离类上编写自定义==实现?

同步问题,发送Api Call之前未设置idToken

同时具有每个文本的标识符的文本组的可扩展性标识符

如何异步返回视图?什么?

如何在SWIFT Memory中处理对VAR数组的更新(对COW感到困惑)

如何写一个;风格;视图修饰符,它会影响特定类型的所有嵌套视图?

关闭 SwiftUI TabView 中的子视图

快速并行读取进程 standardOutput 和 standardError 而不会阻塞

Swift计时器未触发

如何使一个 Reality Composer 场景中的分组对象可拖动?

使 Picker 与其他 BinaryInteger 类型兼容

如何在 SwiftUI 中正确实现Collection 夹?

无法分配给属性:absoluteString是一个只能获取的属性

找不到接受提供的参数的/的重载

Swift 中的 PageViewController 当前页面索引

iOS/Swift:如何检测 UITextField 上的touch 动作

快速在 LLDB 中使用 po

Swift 2.0 中的 do { } catch 不处理从这里抛出的错误

使用 JSONEncoder 对类型为 Codable 的变量进行编码

如何快速从另一个视图控制器重新加载表格视图