material-components-ios icon indicating copy to clipboard operation
material-components-ios copied to clipboard

A font scaled by MDCFontScaler can't be set on titleLabel.font

Open wenyuzhang666 opened this issue 5 years ago • 4 comments

The UILabel font setter does not change the font to the one passed as an argument if it's font traits match the existing one.

This means that attempts at setting a font with additional associated objects may fail. We associate objects in our MDCFontScaler APIs to attach the font scale to be used later.

Code snippet to verify UILabel font setter behavior:

UILabel *firstLabel = [UILabel new];
UIFont *firstFont = [UIFont systemFontOfSize:5];
firstLabel.font = firstFont;
UIFontDescriptor *descriptor = [firstFont.fontDescriptor fontDescriptorWithSize:10];
descriptor = [descriptor fontDescriptorWithSize:5];
UIFont *fontRevised = [UIFont fontWithDescriptor:descriptor size:5.0];
firstLabel.font = fontRevised; // font on firstLabel not changed.

Internal data

wenyuzhang666 avatar May 20 '19 16:05 wenyuzhang666

The title doesn't have a [Component] prefix.

The work around is to set the label's font to nil before you set the new font so that you force a new value being added.

randallli avatar May 20 '19 18:05 randallli

A better workaround is to use a real font: [UIFont systemFontOfSize:1]

randallli avatar May 20 '19 18:05 randallli

Similarly, this also affected UIKit-based Dynamic Type fonts (until the bug was fixed in iOS 13.1). For example:

UIFont *font = [UIFont fontWithName:@"Zapfino" size:14.0];
UIFont *dynamicTypeFont = [UIFontMetrics.defaultMetrics scaledFontForFont:font];

UILabel *label = [[UILabel alloc] init];
label.font = font;
label.font = dynamicTypeFont;

// Fails before iOS 13.1.
XCTAssertEqual(label.font, dynamicTypeFont);

It would be great if Material Design could introduce a category on UILabel called mdc_setFont: that implements a workaround for both the UIKit bug and this Material-specific issue. Then, MDCButton, MDCChipView, etc. as well as external code could use the method to properly set the font.

(Also affected are UITextField/MDCTextField.)

fumoboy007 avatar Jan 20 '21 23:01 fumoboy007