How come I get "Cannot convert value of type 'Font.TextStyle' to expected argument type 'Font?'" when trying to apply a TextStyle from a Binding with `.font()`?

I'm building a settings page and simply want an active preview display embedded into a larger Font Settings View that has:

  • editable text (so TextField)
  • rendering of corresponding Apple provided TextStyle (so ask to keep with DynamicType guidelines)
struct PairingDisplayView: View {
  @Binding var displayStyle: Font.TextStyle
  @State var displaySample = "This is a title"
  @State var bodySample = "Here's some body text to elaborate the font paring preview"
  
  var body: some View {
    VStack(alignment: .leading) {
      Group {
        TextField(
          "display",
          text: $displaySample
        )
        .font(displayStyle)
        TextField(
          "body",
          text: $bodySample
        )
        .font(.body)
      }
      .padding()
    }
    .overlay(
      RoundedRectangle(cornerSize: CGSize(width: 20, height: 20))
        .strokeBorder()
        .foregroundColor(.cyan)
    )
    .padding()
  }
}

I have a @State var selectedSystemStyle: Font.TextStyle = .caption2 that later feeds the said Binding... but I can't get over how confusing it is to me that a Font.TextStyle is not acceptable for the .font() modifier considering it's a Font and I appropriately call .font(displayStyle)

Am I missing something fundamental here?

Accepted Reply

Oh! I understand what happened: I confused Font.TextStyle for the static let properties of the same name in Font! Oops :)

Replies

.font() expect a font, not a fontStyle.

See doc for font modifier:

func font(_ font: Font?) -> Text

If you change your code to

@Binding var displayFont: Font = .caption2

and feed the binding with:

selectedSystemFont: Font = .caption2

That should work.

  • .font() does accept Font.TextStyle (https://developer.apple.com/documentation/swiftui/font/textstyle).

    I specify Font.TextStyle, because I have a Picker in the parent view that'll determine selectedSystemFont, and it does not register state change from the ForEach without it.

    Picker(
      selection: $selectedSystemStyle) {
           ForEach(Font.TextStyle.allCases, id: \.self) { appleTextStyle in
                  Text(appleTextStyle.rawValue).tag(appleTextStyle)
           }
       }
    
Add a Comment

Oh! I understand what happened: I confused Font.TextStyle for the static let properties of the same name in Font! Oops :)