Search code examples
iosautolayoutuilabelvertical-alignmentbaseline

Align two labels vertically with different font size


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:

baseline not correctly aligned

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]|

The above constraints leads to

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?


Solution

  • 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: enter image description here