首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SwiftUI自定义字体-所有字体类型都使用新字体

SwiftUI自定义字体-所有字体类型都使用新字体
EN

Stack Overflow用户
提问于 2021-01-27 02:30:53
回答 1查看 124关注 0票数 1

我目前在我的应用程序中使用自定义字体,但我发现不得不到处使用.font(Font.custom("Montserrat-Regular", size: 16))有点令人沮丧。有没有办法我可以设置整个应用程序使用这种字体,我可以简单地使用.font(.system(size: 16)),甚至使用像.font(.caption)这样的标准大小,它将使用自定义字体?

我实际上已经在我的ContentView上设置了.font(Font.custom("Montserrat-Medium", size: 16)),如下所示,这允许我在任何地方使用这种字体,但大小始终是16,当我更改它时,字体将恢复为默认字体。

代码语言:javascript
复制
@main
struct AppName: App {
  var body: some Scene {
    WindowGroup {
        ContentView()
            .font(Font.custom("Montserrat-Regular", size: 16))
    }
  }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-27 06:12:12

您可以使用自定义类型创建常量,例如AppFont,如下所示:

代码语言:javascript
复制
enum AppFont {

    static let header       = Font.custom(Raleway.extraBold.weight,    size: 40)
    static let header2      = Font.custom(Raleway.extraBold.weight,    size: 30)
    static let title        = Font.custom(Raleway.bold.weight,         size: 32)
    static let title2       = Font.custom(Raleway.extraBold.weight,    size: 22)
    static let subtitle     = Font.custom(Raleway.bold.weight,         size: 16)
    static let body         = Font.custom(Raleway.medium.weight,       size: 17)
    static let body2        = Font.custom(Raleway.regular.weight,      size: 17)
    static let footnote     = Font.custom(Raleway.regular.weight,      size: 16)
    static let footnote2    = Font.custom(Raleway.regular.weight,      size: 13)
    
    static var custom: (Raleway, CGFloat) -> Font = { (weight, size) in
        return Font.custom(weight.weight, size: size)
    }
}

enum Raleway: String {

    case black        = "Raleway-Black"
    case extraBold    = "Raleway-ExtraBold"
    case bold         = "Raleway-Bold"
    case semiBold     = "Raleway-SemiBold"
    case medium       = "Raleway-Medium"
    case regular      = "Raleway-Regular"
    case light        = "Raleway-Light"
    case extraLight   = "Raleway-ExtraLight"
    case thin         = "Raleway-Thin"
    
    var weight: String { return self.rawValue }
}

用法

代码语言:javascript
复制
Text("Example")
    .font(AppFont.header)

这是我的应用程序的摘录,你可以用你的字体替换Raleway,即Montserrat或任何字体。给你举个例子。

备注

我不建议简单地扩展Font。我发现更清楚的是,对任何应用程序都有自定义类型-自定义的东西。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65907158

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档