用不同的字体大小垂直对齐两个标签 [英] Align two labels vertically with different font size

查看:539
本文介绍了用不同的字体大小垂直对齐两个标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个父的UIView 其中,我把两个标签就可以了。每个标签只有一个行可以在这里看到:

I have a parent UIView where I place two labels on it. Each of these labels only has one line as can be seen here:

现在的问题是,基线是错误的。我使用的自动布局和问题是如何使我的约束应该像在这种情况下?尤其是标签的verticaly定位。这是我目前拥有的约束:

The problem now is that the baseline is wrong. I'm using auto layout and the question is how should my constraints should look like in this case? Especially the verticaly positioning of the labels. These are the constraints I currently have:

H:|-[title]-2-[description]-(>=5)-| //with NSLayoutFormatOptions.AlignAllFirstBaseline
V:|[title]|
V:|[description]|

以上限制导致

无法同时满足约束条件。

Unable to simultaneously satisfy constraints.

由于定心和第一基线约束互相争斗。标签应以母公司的全高度,但使用不同的字体大小。

because the centering and the first baseline constraint are fighting each other. The labels should take the full height of the parent, but with different font size.

我试过脚的标签贴到顶部/底部但这并不适用于所有情况下工作。

I tried to pin the labels to the top/bottom but that doesn't work for all cases.

应该如何定位垂直标签我?

How should I vertically position my labels?

推荐答案

而不是使用两种不同的标签,你可以使用AttributedString富文本。这里有一个例子:

Instead of using two different label for rich text you can use AttributedString. Here is a example:

- (NSMutableAttributedString*)getRichText {
    NSString *str1 = @"I am bold ";
    NSString *str2 = @"I am simple";

    NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:[str1 stringByAppendingString:str2]];

    UIFont *font1=[UIFont fontWithName:@"Helvetica-Bold" size:30.0f];
    UIFont *font2=[UIFont fontWithName:@"Helvetica" size:20.0f];
    NSInteger l1 = str1.length;
    NSInteger l2 = str2.length;
    [attString addAttribute:NSFontAttributeName value:font1 range:NSMakeRange(0,l1)];
    [attString addAttribute:NSFontAttributeName value:font2 range:NSMakeRange(l1,l2)];
    return attString;
}

在查看并加载您可以设置字符串如下标签:

In View did load you can set the string to label as below:

UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 50)];
[self.view addSubview:textLabel];
textLabel.attributedText = [self getRichText];

输出:

Output:

这篇关于用不同的字体大小垂直对齐两个标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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