0

I am trying to give the font size, style as per typography & weight as per the resolution of screen dynamically.

I tried:

title_home.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.title1)
 subtitle_home.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.title2)
 subtitle1_home.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.title2)
subtitle2_home.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.title2)

But am getting the text in normal regular size. I need the title as bold with some size, and it should change as per the resolution of screen.

4
  • Hi.. this code snippet you shared is fine. Can you share some other information like where your calling the code.. or if you can share the whole controller code.. i think the font property is getting overridden from some other part of your code
    – ayon.gupta
    Apr 19, 2019 at 4:49
  • I am calling this code in viedidload method of viewcontroller
    – Navya
    Apr 19, 2019 at 4:54
  • Are you saying you want a smaller font on an iPhone 5 and a much larger font on an iPad Pro?
    – rmaddy
    Apr 19, 2019 at 4:55
  • And are you sure the labels fonts are not getting overridden?? i can see it working at my end. The fields "title_home", "subtitle_home", "subtitle1_home", "subtitle2_home" , how are you setting text to thee fields?
    – ayon.gupta
    Apr 19, 2019 at 4:58

1 Answer 1

1

You can get bold/italic/etc preferred font based on descriptor, something like this:

    let descriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: .headline)
        .addingAttributes([.traits : [UIFontDescriptor.TraitKey.weight: UIFont.Weight.semibold]])

    let semiboldFont = UIFont(descriptor: descriptor, size: 0)

    print(semiboldFont)
    //<UICTFont: 0x7fe03300cc30> font-family: ".SFUIText-Semibold"; font-weight: bold; font-style: normal; font-size: 17.00pt

hope that helps

2
  • is this possible for semibold??if I keep the font size same, will it vary the size as per the resolution??
    – Navya
    Apr 19, 2019 at 11:40
  • Updated the answer to add more flexibility
    – Mindaugas
    Apr 19, 2019 at 12:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.