0

I'm working with and interface built using size classes and autolayout. One of the issues I'm encountering is that I can no longer use a fixed font size for the text fields - less text will be visible on smaller screens.

One of the solutions is to use "Adjust to Fit", however that option only works when there's enough text to overflow the text field horizontally. enter image description here

What is the correct solution for the font size to use when the UITextField size at runtime is unknown?

Alex Stone
  • 46,408
  • 55
  • 231
  • 407

2 Answers2

3

Am using a custom class for all labels and am assigning two properties at the time of designing. One is autoFont and another is the fontSize which is currently the font size in iPhone 4 inch xib at design time. Here is the class.

the .h file

#import <UIKit/UIKit.h>

@interface CustomLabel : UILabel

@property (nonatomic) IBInspectable BOOL autoFont;

@property (nonatomic) IBInspectable CGFloat fontSize;

@end

and here is the .m file

#import "CustomLabel.h"

@implementation CustomLabel

@synthesize autoFont;
@synthesize fontSize;

- (void)layoutSubviews
{
    [super layoutSubviews];

    if (autoFont) {
        float newFontSize = [UIScreen mainScreen].bounds.size.height * (fontSize / 568.0);
        if ([UIScreen mainScreen].bounds.size.height < 500) {
            newFontSize = [UIScreen mainScreen].bounds.size.height * (fontSize / 480.0);
        }
        self.font = [UIFont fontWithName:self.font.fontName size:newFontSize];
    }
}

@end

i think this is the easiest solution for this kind of problem and also i have did this same thing with buttons and text fields by using custom class.

Mahesh Agrawal
  • 3,348
  • 20
  • 34
  • logic is, increase the font size according to the ratio of device scaling by comparing UIScreen height with the current height of xib at design time. – Mahesh Agrawal Dec 12 '16 at 10:53
2

I'm aware of non interface builder soultion. You get height of your screen and set label's font accordingly.

CGFloat windowHeight = [UIApplication sharedApplication].delegate.window.frame.size.height;
label.font = [UIFont fontWithName:@"Font-Name" size:windowHeight / 10];
Eluss
  • 512
  • 3
  • 5