使用不同的字体大小垂直对齐两个标签

时间:2015-05-26 09:51:58

标签: ios autolayout uilabel vertical-alignment baseline

我有一个父UIView,我在其上放置了两个标签。这些标签中的每一个只有一行,如下所示:

baseline not correctly aligned

现在的问题是基线是错误的。我正在使用自动布局,问题是在这种情况下我的约束应该如何?特别是标签的垂直定位。这些是我目前的限制因素:

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

以上限制导致

  

无法同时满足约束条件。

因为中心和第一个基线约束相互争斗。标签应采用父级的完整高度,但字体大小不同。

我试图将标签固定在顶部/底部,但这并不适用于所有情况。

我应该如何垂直放置标签?

3 个答案:

答案 0 :(得分:2)

您可以使用AttributedString代替为富文本使用两个不同的标签。这是一个例子:

- (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;
}

在View中加载后,您可以将字符串设置为标签,如下所示:

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

输出: enter image description here

答案 1 :(得分:1)

要查看会发生什么,请将标签的背景设为黄色。你有不明确的约束。

要修复它,请删除最后一个垂直约束。你不需要它。

这在我的测试操场中有效:

let titleLabel = UILabel()
titleLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
titleLabel.font = UIFont.boldSystemFontOfSize(30)
titleLabel.text = "title"

hostView.addSubview(titleLabel)

let descriptionLabel = UILabel()
descriptionLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
descriptionLabel.font = UIFont.boldSystemFontOfSize(20)
descriptionLabel.text = "description"

hostView.addSubview(descriptionLabel)

let views = ["title": titleLabel, "description": descriptionLabel]
NSLayoutConstraint.activateConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|-[title]-2-[description]-(>=5)-|", options: NSLayoutFormatOptions.AlignAllFirstBaseline, metrics: nil, views: views))
NSLayoutConstraint(item: titleLabel, attribute: .CenterY, relatedBy: .Equal, toItem: hostView, attribute: .CenterY, multiplier: 1.0, constant: 0.0).active = true

结果:Screenshot

答案 2 :(得分:0)

你需要做的事情很简单。 你需要两个标签(对象)的高度相同。

为此,请为第一个标签添加约束(例如40 px)。 完成后,选择第一个和第二个标签然后在屏幕底部的约束菜单中(左边的一个,添加新的对齐约束)选择顶边和底边。

然后你可以根据需要设置你的宽度顶部等。

享受

相关问题