bubibu bubibu - 18 days ago 4
Objective-C Question

Objective c label.numberOflines is not working

No matter I set the number of lines to 0 or to 100, it just won't change and the texts remain ... at the end. I've tried NSLineBreakByWordWrapping but it just removed the ... and do nothing.

UILabel *label = [[UILabel alloc] init];
[cell.contentView addSubview:label];
label.text = myString;
label.frame = CGRectMake(17, 42, 200, 30);
[label sizeToFit];
label.lineBreakMode = NSLineBreakByWordWrapping;
label.numberOfLines = 0;

Answer

Use this

UILabel *label = [[UILabel alloc] init];

label.text = @"myStringsdsdvsvdsdvsdvsdndbndbnbdnbdnbdnpopopoploplklioolnhbfghrmyString";

label.numberOfLines = 0;
label.frame = CGRectMake(0, 50, 320, 568);

[self.view addSubview:label];

label.frame = CGRectMake(0, 42, [self widthForLabel:label withText:label.text], [self height:label withText:label.text]);

label.backgroundColor = [UIColor redColor];

for Dynamic width

-(CGFloat)widthForLabel:(UILabel *)label withText:(NSString *)text
{
    if (text.length > 0)
    {
        NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName:label.font}];
        CGRect rect = [attributedText boundingRectWithSize:(CGSize){label.frame.size.width, CGFLOAT_MAX}
                                                   options:NSStringDrawingUsesLineFragmentOrigin
                                                   context:nil];

        return ceil(rect.size.width);

    }

return 0;

}

for dynamic height

  -(CGFloat)height:(UILabel *)label withText:(NSString *)text
{
    if (text.length > 0)
    {
        NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName:label.font}];
        CGRect rect = [attributedText boundingRectWithSize:(CGSize){label.frame.size.width, CGFLOAT_MAX}
                                                   options:NSStringDrawingUsesLineFragmentOrigin
                                                   context:nil];

        return ceil(rect.size.height);
    }

    return 0;
}

enter image description here

here problem is you need to initialize label with some frame like this

    label.frame = CGRectMake(0, 50, 320, 568);

now when you have added label to your view then calculate dynamic width and height of label and again set the frame.

Hope it will work.

Comments