Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto Layout UILabels

I have three UILabels in my custom UITableViewCell. It might be that some UILabels will be empty (label.text == @"")

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"EventCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];


        NSString *key = [[keysArray objectAtIndex:indexPath.section] description];

        UILabel *nameLabel = (UILabel *)[cell viewWithTag:100];
        namelabel.text = @"Label 1";

        UILabel *locationLabel = (UILabel *)[cell viewWithTag:101];
        location.text = @"Label 2";

        UILabel *timeLabel = (UILabel *)[cell viewWithTag:102];
        timeLabel.text = @"";

        return cell;
}

How can I centre all non-empty UILabels vertically in the cell using auto-layout?

This is how it looks with three labels

This is how it looks with three labels:

How it looks when one of UILables is empty

How it looks when one of <code>UILables</code> is empty

And this is how I want it to look:

And this is how I want it to look:

like image 335
Oleg Avatar asked Oct 22 '22 17:10

Oleg


1 Answers

This is tricky to achieve, but a simple shortcut may be to have a single label instead, with three lines of text, constrained to fill the whole height of the cell. The label will then auto-center its contents vertically.

You'd have three string properties on the cell instead of three labels, and your setters would build the final string (using \n for new lines) and set the label's text.

If each line of text has different styling, no problem, as you can use attributed strings.

like image 124
jrturton Avatar answered Oct 29 '22 22:10

jrturton