Scaling UIFont size relative to screen size

I allow users to add a UITextField on top of their images, such as UITextField .

I designed it so that their images are perfect squares depending on the screen size of the iPhone. So on my iPhone 5S it will be 320x320 UIImageView . IPhone 6 will be 375x375 UIImageView . Images placed on large phones with a screen will be reduced using ImageView when viewed on a smaller phone.

How to adjust the font size that will be related to the width of the screen?

I am currently using:

 [UIFont systemFontOfSize:16.0] 

Is it appropriate to use ?:

 [UIFont systemFontOfSize:self.frame.size.width/20]; 

I'm not sure what dot size actually represents the font size. I also found [UIFont preferredFontForTextStyle:UIFontTextStyleBody]; but I'm not sure if this is what i'm looking for.

thanks

+5
source share
3 answers

UIFont has a method that gives you the size of the system font. You can then use this to dynamically calculate a reasonable font size. What is reasonable will test and experiment for you. This will result in something like this:

 UIFont *font = [UIFont systemFontOfSize:[UIFont systemFontSize]*[UIScreen mainScreen].bounds.width/375.0]; 
+1
source

This is a bit overkill, but to make sure my text fits on the screen, I do a loop to find out the font size (because I represent this text in a custom drawRect implementation (maybe the best way if you use UILabel )

  float FACTOR = 0.5f; UIFont *font = [UIFont fontWithName:_fontName size:_maximumSize]; // paragraph for both NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping; paragraphStyle.alignment = NSTextAlignmentCenter; // attributes for back NSDictionary *attributes = @{NSFontAttributeName : font, NSParagraphStyleAttributeName : paragraphStyle}; CGSize textSize = [_text sizeWithAttributes:attributes]; // reduce font size until the text fits in bounds while(textSize.width > _view.bounds.size.width * FACTOR || textSize.height > _view.bounds.size.height * FACTOR) { _maximumSize--; font = [font fontWithSize:_maximumSize]; attributes = @{NSFontAttributeName : font, NSParagraphStyleAttributeName : paragraphStyle}; textSize = [_progressText sizeWithAttributes:attributes]; } 

Just adjust the FACTOR so that the font matches the borders of the views.

+1
source

In Swift 4:

 let textToFit: String = ... let maxWidth: CGFloat = ... var font: UIFont = ... var textAttributes: [NSAttributedStringKey: Any] = [ .font: font, ... ] while (textToFit.size(withAttributes: textAttributes).width > maxWidth) { font = font.withSize(font.pointSize - 1.0) textAttributes[.font] = font } // You have your font now! 
0
source

Source: https://habr.com/ru/post/1206394/


All Articles