Line up three UILabels next to each other and each label can be multiline

一曲冷凌霜 提交于 2019-12-23 04:52:10

问题


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 !


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/19837522/line-up-three-uilabels-next-to-each-other-and-each-label-can-be-multiline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!