Line up three UILabels next to each other and each

2019-06-09 04:18发布

I'am working on a project where I need to line up 3 UILabels next to each other. Let me explain it with an example.

I have for example the following sentence. "Tim Moore commented on the little bear story" Now my three UILabels going to contain:

LABEL 1 --> Tim Moore
LABEL 2 --> commented on
LABEL 3 --> the little bear story

another example:

Dave Smits likes the status "We and only we can me a knew future and only we nobody else can make changes, so don't stop now !"

LABEL 1 --> Dave Smits
LABEL 2 --> likes the status
LABEL 3 --> "We and only we can me a knew future and only we nobody else can make changes, so don't stop now !"

Like you can see in the second example the sentence is much longer.

My question is now how can I line these three UILabels line up after each other so that I get a nice sentence. The reason why I separate it in three UILabels is because I need to set UITapgestures on each UILabel.

I'm working inside a custom UITableviewCell which is using autolayout.

Any help would be appreciated !

2条回答
欢心
2楼-- · 2019-06-09 04:44

You can use that piece of code to get your labels lined up. Set numberOfLines:0 to let them be multi-line.

-(void)adjustLabels
{
    [self.label1 setText:@"Dave Smits"];
    [self.label2 setText:@"likes the status"];
    [self.label3 setText:@"We and only we can me a knew future and only we nobody else can make changes, so don't stop now !"];

    [self.label1 setNumberOfLines:0];
    [self.label1 sizeToFit];
    CGRect frameFor2 = self.label2.frame;
    frameFor2.origin.x = self.label1.frame.origin.x + 3.f; //add some space between labels
    [self.label2 setFrame:frameFor2];

    [self.label2 setNumberOfLines:0];
    [self.label2 sizeToFit];
    CGRect frameFor3 = self.label3.frame;
    frameFor3.origin.x = self.label2.frame.origin.x + 3.f;
    [self.label3 setFrame:frameFor3];

    [self.label3 setNumberOfLines:0];
    [self.label3 sizeToFit];
}

sizeToFit method does not work with auto layout, you can have a look at another answer from SO to fix it.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-06-09 05:04

Make a custom layout of your cell and line up the UILabels with constraints inside the custom cell. Since you are in a custom layout, the constraints should do the trick.

查看更多
登录 后发表回答