自动版式连接两个UILabels具有相同的字体大小 [英] AutoLayout link two UILabels to have the same font size

查看:148
本文介绍了自动版式连接两个UILabels具有相同的字体大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个UILabels彼此下一行与左,右调整,使它看起来像下面。

I have two UILabels next to each other in row with left and right adjustments so that it looks like below.

 |-Some text left adjusted----------some other text right adjusted-|

两种标签有所adjustsFontSizeToFitWidth = YES,和被连接到彼此具有以下约束

Both labels have adjustsFontSizeToFitWidth = YES and are linked to each other with the following constraint

[NSLayoutConstraint constraintWithItem:_rightLabel
                    attribute:NSLayoutAttributeLeft
                    relatedBy:NSLayoutRelationGreaterThanOrEqual
                    toItem:_leftLabel
                    attribute:NSLayoutAttributeRight
                    multiplier:1
                    constant:10]

使它们占用尽可能多的空间,因为他们可以和如果没有对原始字体大小,使得没有文本被截断它将会降低由于adjustsFontSizeToFitWidth足够的空间。

So that they take up as much space as they can and if there is not enough space for the original font size it will be lowered thanks to adjustsFontSizeToFitWidth so that no text is truncated.

我的问题是,当一个人需要降低其字体大小,由于长文本我想其他标签,使两者的大小相同,而不是一个在另一个的存在也许两倍大小降低其字体大小为好。我想约束的字体大小,以及相匹配,但可惜我不知道怎么这一点,任何想法?

My problem is that when one needs to lower its font size due to long text i want the other label to lower its font size as well so that both are the same size instead of one being perhaps twice the size of the other. I would like to constraint the font size as well to match but alas i do not know how to this, any ideas?

推荐答案

从<一个href=\"https://developer.apple.com/library/ios/documentation/uikit/reference/UILabel_Class/Reference/UILabel.html#//apple_ref/occ/instp/UILabel/adjustsFontSizeToFitWidth\">UILabel在 adjustsFontSizeToWidth 文档:

通常情况下,标签文本绘制与您在字体属性指定字体。如果该属性设置为YES,但是,并在文本属性中的文本超过标签的边框,接收机开始减小字体大小,直到该字符串符合或达到最小字体大小。

Normally, the label text is drawn with the font you specify in the font property. If this property is set to YES, however, and the text in the text property exceeds the label’s bounding rectangle, the receiver starts reducing the font size until the string fits or the minimum font size is reached.

我从这个推断,更新的字体在绘图时计算的,而字体属性为只读,不能写入。因此,我认为安德鲁的建议,使用志愿上的字体属性将无法工作。

I infer from this that the updated font is calculated at drawing time, and the font property is only read, not written to. Therefore, I believe the suggestion by Andrew to use KVO on the font property will not work.

因此​​,为了达到你想要的结果,你需要计算调整后的字体大小。

Consequently, to achieve the result you want, you'll need to calculate the adjusted font size.

由于杰克逊在评论中指出,这个很方便的NSString方法获得实际的字体已经去$ P $在iOS的7技术上pcated,你仍然可以使用它,直到它删除。

As Jackson notes in the comments, this very convenient NSString method to get the actual font has been deprecated in iOS 7. Technically, you could still use it until it's removed.

另一种方法是通过字体的尺度循环,直到你找到一个适合这两个标签。我能得到它做工精细; 这里有一个示例项目,显示我是如何做的

Another alternative is to loop through font scales until you find one that will fit both labels. I was able to get it working fine; here's a sample project that shows how I did it.

此外,这里是万一code链接一旦停止工作:

Also, here's the code in case that link ever stops working:

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:_rightLabel
                                                                  attribute:NSLayoutAttributeLeft
                                                                  relatedBy:NSLayoutRelationGreaterThanOrEqual
                                                                     toItem:_leftLabel
                                                                  attribute:NSLayoutAttributeRight
                                                                 multiplier:1
                                                                   constant:10];

    [self.view addConstraint:constraint];
}

- (IBAction)makeRightLabelLongerPressed:(id)sender {
    self.rightLabel.text = @"some much longer right label text";
}

- (IBAction)adjustLabelSizes:(id)sender {
    NSLog(@"Attempting to adjust label sizes…");

    CGFloat minimumScaleFactor = fmaxf(self.rightLabel.minimumScaleFactor, self.leftLabel.minimumScaleFactor);;
    UIFont * startingFont = self.rightLabel.font;

    for (double currentScaleFactor = 1.0; currentScaleFactor > minimumScaleFactor; currentScaleFactor -= 0.05) {
        UIFont *font = [startingFont fontWithSize:startingFont.pointSize * currentScaleFactor];
        NSLog(@"  Attempting font with scale %f (size = %f)…", currentScaleFactor, font.pointSize);

        BOOL leftLabelWorks = [self wouldThisFont:font workForThisLabel:self.leftLabel];
        BOOL rightLabelWorks = [self wouldThisFont:font workForThisLabel:self.rightLabel];
        if (leftLabelWorks && rightLabelWorks) {
            NSLog(@"    It fits!");
            self.leftLabel.font = font;
            self.rightLabel.font = font;
            return;
        } else {
            NSLog(@"    It didn't fit. :-(");
        }

    }

    NSLog(@"  It won't fit without violating the minimum scale (%f), so set both to minimum.  Some text may get truncated.", minimumScaleFactor);

    UIFont *minimumFont = [self.rightLabel.font fontWithSize:self.rightLabel.font.pointSize * self.rightLabel.minimumScaleFactor];
    self.rightLabel.font = minimumFont;
    self.leftLabel.font = minimumFont;
}

- (BOOL) wouldThisFont:(UIFont *)testFont workForThisLabel:(UILabel *)testLabel {
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:testFont, NSFontAttributeName, nil];
    NSAttributedString *as = [[NSAttributedString alloc] initWithString:testLabel.text attributes:attributes];
    CGRect bounds = [as boundingRectWithSize:CGSizeMake(CGRectGetWidth(testLabel.frame), CGFLOAT_MAX) options:(NSStringDrawingUsesLineFragmentOrigin) context:nil];
    BOOL itWorks = [self doesThisSize:bounds.size fitInThisSize:testLabel.bounds.size];
    return itWorks;
}

- (BOOL)doesThisSize:(CGSize)aa fitInThisSize:(CGSize)bb {
    if ( aa.width > bb.width ) return NO;
    if ( aa.height > bb.height ) return NO;
    return YES;
}

该方法可以平凡重构到它取代了杰克逊联系到德precated方法的类中的方法。

This approach could be trivially refactored into a category method that replaces the deprecated method linked to by Jackson.

这篇关于自动版式连接两个UILabels具有相同的字体大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆