0

我有两个UILabels。其中之一已adjustsFontSizeToFitWidth启用。如何将字体复制到另一个UIlabel

UILabel *labelLong = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
labelLong.text = @"Very very long text";
labelLong.adjustsFontSizeToFitWidth = YES;

UILabel *labelShort = [[UILabel alloc] initWithFrame:CGRectMake(50, 0, 50, 50)];
labelShort.text = @"LOL";

只是从另一个标签复制字体似乎不起作用:

labelShort.font = labelLong.font
4

2 回答 2

1

不幸的是,如果你记录 labelLong 的字体,它仍然显示为默认大小 17,所以你不能用简单的方法做到这一点。我发现这样做的一种方法是从原始字体开始,并循环通过较小的字体大小,直到文本的边界矩形宽度小于标签文本矩形的宽度(从 textRectForBounds:limitedToNumberOfLines 获得:)。这段代码对我有用,但我还没有彻底测试过。我每次通过循环将字体大小调整 0.1 以获得合理准确的答案。

@interface ViewController ()
@property (strong,nonatomic) UILabel *labelLong;
@property (strong,nonatomic) UILabel *labelShort;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.labelLong = [[UILabel alloc] initWithFrame:CGRectMake(20, 50, 50, 50)];
    self.labelLong.text = @"Very text";
    self.labelLong.adjustsFontSizeToFitWidth = YES;
    [self.view addSubview:self.labelLong];

    self.labelShort = [[UILabel alloc] initWithFrame:CGRectMake(20, 70, 50, 50)];
    self.labelShort.text = @"Very";
    [self.view addSubview:self.labelShort];
    [self updateFont];
}

-(void)updateFont {
    NSStringDrawingContext *ctx = [NSStringDrawingContext new];
    ctx.minimumScaleFactor = 1.0;
    UIFont *startingFont = self.labelLong.font;
    NSString *fontName = startingFont.fontName;
    CGFloat startingSize = startingFont.pointSize;
    for (float i=startingSize*10; i>1; i--) {
        UIFont *font = [UIFont fontWithName:fontName size:i/10];
        CGRect textRect = [self.labelLong.text boundingRectWithSize:self.labelLong.frame.size options:NSStringDrawingTruncatesLastVisibleLine attributes:@{NSFontAttributeName:font} context:ctx];
        if (textRect.size.width < [self.labelLong textRectForBounds:self.labelLong.bounds limitedToNumberOfLines:1].size.width) {
            NSLog(@"Font size is: %f", i/10);
            NSLog(@"Font rect is: %@",NSStringFromCGRect(textRect));
            self.labelShort.font = [UIFont fontWithName:fontName size:i/10];
            break;
        }
    }
}
于 2013-11-06T06:08:17.023 回答
0

得到长标签的字体名称和字体大小后,我们可以将它们分配给另一个标签。
你可以这样试试

NSString *fName = self.labelLong.font.fontName;
CGFloat fSize = self.labelLong.font.pointSize;
[labelShort setFont:[UIFont fontWithName:fName size:fSize]];
于 2013-11-06T04:43:23.800 回答