如何使用字体修饰符? SwiftUI中的大写字母和字体大小

时间:2020-03-19 19:45:26

标签: ios swift swiftui swift5

我正在尝试使用修饰符为我的应用创建一些默认字体。如果有更简单的方法,我很想知道。目前,我有

struct PrimaryLabel: ViewModifier {
    func body(content: Content) -> some View {
        content
            .font(Font.body.smallCaps())
            .font(.system(size: 20, weight: .light, design: .serif)) // this is not working. Only the first one will '.font' will work

    }
}

可用性:

Text("Hello World").modifier(PrimaryLabel())

是否可以更改字体类型(例如,使用AmericanTypewriter-Light字体),全部大写并使用weight: .light, design: .serif,粗体等样式?我不想定义每个文本。结构中的第二个.font修饰符不起作用。

2 个答案:

答案 0 :(得分:1)

第一个修饰符仅可见,这是合乎逻辑的,请尝试应用少量,background或.foregroundColor...。它的工作方式相同。

尝试

VStack {
    Text("ALFA").font(.largeTitle)
    Text("Beta").foregroundColor(Color.red)
}
.font(.system(size: 150))
.foregroundColor(Color.blue)

enter image description here

您可以使用不同的初始化程序创建字体

init(CTFont)

从平台字体实例获取字体。

static func system(Font.TextStyle, design: Font.Design) -> Font

获取具有给定样式和设计的系统字体。

static func system(size: CGFloat, weight: Font.Weight, design: Font.Design) -> Font

指定要使用的系统字体,以及样式,粗细和要应用于文本的任何设计参数。

static func custom(String, size: CGFloat) -> Font

获取具有给定名称和大小的自定义字体。

您可以进一步设置文本样式

设置文本视图的样式

func bold() -> Text

对文本应用粗体。

func italic() -> Text

在文本上加上斜体。

func fontWeight(Font.Weight?) -> Text

设置文本的字体粗细。

func baselineOffset(CGFloat) -> Text

设置文本的基线偏移。

func tracking(CGFloat) -> Text

设置文本的跟踪。

func kerning(CGFloat) -> Text

设置两个字符之间的间距或字距。

func underline(Bool, color: Color?) -> Text

在文本上加上下划线。

func strikethrough(Bool, color: Color?) -> Text

对文本应用删除线。

警告!! 并非所有组合都受支持! 参见How to apply .italic() to .largeTitle Font?

答案 1 :(得分:0)

extension View {
    func primaryLabelStyle(_ weight: Font.Weight) -> some View {
        return self.modifier(PrimaryLabel(weight: weight))
    }
}

struct PrimaryLabel: ViewModifier {
    let weight: Font.Weight
    func body(content: Content) -> some View {
        content
            .font(Font.body.smallCaps())
            .font(.system(size: 20, weight: weight, design: .serif)) // this is not working. Only the first one will '.font' will work

    }
}

Text("Hello World").primaryLabelStyle(.light)