UILabel: adjust font size to height with AutoLayout

為{幸葍}努か 提交于 2019-12-09 20:08:34

问题


I'd like to have several labels one below the other. The are sized with AutoLayout, I'd like to have the font size as big as possible. adjustsFontSizeToFitWidth only works for the width, but the I get the following result


回答1:


You can re-calculate your content height by calling (it may be a little easier to manage by having your layout built as a tableview, if it isn't already):

[cell.contentView systemLayoutSizeFittingSize:UILayoutFittingExpandedSize].height;

I've also had to hard code this for a specific purpose (added as a UIFont category):

+ (int)contentSizeHeightForItem {
    NSString *cat = [[UIApplication sharedApplication] preferredContentSizeCategory];
    if([cat isEqualToString:UIContentSizeCategoryExtraSmall]) {
        return 84;
    } else if([cat isEqualToString:UIContentSizeCategorySmall]) {
        return 86;
    } else if([cat isEqualToString:UIContentSizeCategoryMedium]) {
        return 88;
    } else if([cat isEqualToString:UIContentSizeCategoryLarge]) {
        return 92;
    } else if([cat isEqualToString:UIContentSizeCategoryExtraLarge]) {
        return 94;
    } else if([cat isEqualToString:UIContentSizeCategoryExtraExtraLarge]) {
        return 98;
    } else if([cat isEqualToString:UIContentSizeCategoryExtraExtraExtraLarge]) {
        return 102;
    }
    return 80;
}



回答2:


If your font is constant, you can calculate the necessary height of the labels from the font like so:

UIFont *font = [UIFont fontWithName:@"Helvetica" size:18];
UILabel *label = [UILabel new];
[label setFont:font];
[view addSubview:label];

double labelHeight = font.pointSize + fabs(font.descender);
[view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[label(labelHeight)]"
                                                             options:0
                                                             metrics:@{@"labelHeight" : @(labelHeight)}
                                                               views:@{@"label" : label}]];

This will guarantee that the full height of the font will be taken into account when setting constraints.



来源:https://stackoverflow.com/questions/21270091/uilabel-adjust-font-size-to-height-with-autolayout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!