swiftxcodetextswiftuifont-size

Change font size base on device


is there any way to understand which type of Device the user is using.

I would like to use it in order to change the font size for the iPhone8 , if device == "iPhone8" { use Textfontsize 20 } else { use 10}

thanks a lot


Solution

  • Damiano,

    Changing the font size based on the device isn't a good plan, what happens when Apple launch a new device. What does your user who uses accessibility and wants to make the font larger do? Maybe you have a user who wants small fonts cause he is using a 12inch iPad in dual screen mode.

    Use dynamic fonts, and let the user choose the size they like :) Here is cut'n'paste from an article on that very same subject.

    https://www.hackingwithswift.com/quick-start/swiftui/how-to-use-dynamic-type-with-a-custom-font

    @available(iOS 13, macCatalyst 13, tvOS 13, watchOS 6, *)
    struct ScaledFont: ViewModifier {
    @Environment(\.sizeCategory) var sizeCategory
    var name: String
    var size: CGFloat
    
    func body(content: Content) -> some View {
       let scaledSize = UIFontMetrics.default.scaledValue(for: size)
        return content.font(.custom(name, size: scaledSize))
    }
    }
    
    @available(iOS 13, macCatalyst 13, tvOS 13, watchOS 6, *)
    extension View {
    func scaledFont(name: String, size: CGFloat) -> some View {
        return self.modifier(ScaledFont(name: name, size: size))
    }
    }
    
    struct ContentView: View {
    var body: some View {
        List {
            Text("Hello World")
            Text("Hello World")
                .scaledFont(name: "Georgia", size: 12)
        }
      }
    }