简体   繁体   中英

Single-line UILabel not shrinking (iOS 10)

I've gone through a load of posts on SO for this and nothing is working. Why does "Cheese!" not shrink at all? I checked the bounds of the label at runtime and they're fine. This is a plain (not attributed) UILabel.

This code runs after viewDidAppear .

self.cameraCountdownLabel.numberOfLines = 1;
self.cameraCountdownLabel.font = [UIFont fontWithName:@"OpenSans-Bold" size:300.0];
self.cameraCountdownLabel.adjustsFontSizeToFitWidth = true;
self.cameraCountdownLabel.minimumScaleFactor = 0.1;
self.cameraCountdownLabel.lineBreakMode = NSLineBreakByTruncatingTail;
self.cameraCountdownLabel.text = LocalizedMajor(@"Cheese!",nil);

Why does "Cheese!" not shrink at all?

Without seeing the constraints or frame layout code that set the size of your label, it's hard to say. But it is worth noting that changing the height of a label will not change the font size of the contents to fit. Only width is considered. So if your label gets compressed vertically and you are hoping that the font will shrink to keep the text visible without clipping, you will need to try a different approach like an aspect ratio constraint. Only shrinking the width of a label will trigger a reduction of font size in order to make the text fit horizontally in the space available.

Turns out the label's superview had a constraint for its width that was somehow only priority 749 (optional), and although checking the bounds after the text was set in the debugger, it was indeed (later!) growing its bounds. The fix was to change the superivew's width-constraint's priority to 1000.

For others, the way to debug this was to set a breakpoint after the text was set in the label, check the label's bounds with po labelname , then to add the following code only for debugging to check the bounds again after some time:

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    (breakpoint here)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM