deveLost
deveLost

Reputation: 1171

iOS change number lines of label

I tried to code the number of lines for one label.

I did this :

[lblName setFont:[UIFont fontWithName:@"OpenSans-CondensedLight" size:19]];
[lblName setText:[objet titre]];
[lblName setLineBreakMode:NSLineBreakByWordWrapping];
lblName.numberOfLines = 2;

But it's not running, i've just one line...

Someone to help me plz ?

Upvotes: 1

Views: 1412

Answers (3)

Sujith Thankachan
Sujith Thankachan

Reputation: 3506

Use this method:

- (CGSize)getSizeForText:(NSString *)text maxWidth:(CGFloat)width font:(NSString *)fontName fontSize:(float)fontSize {
    CGSize constraintSize;
    constraintSize.height = MAXFLOAT;
    constraintSize.width = width;
    NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                          [UIFont fontWithName:fontName size:fontSize], NSFontAttributeName,
                                          nil];

    CGRect frame = [text boundingRectWithSize:constraintSize
                                      options:NSStringDrawingUsesLineFragmentOrigin
                                   attributes:attributesDictionary
                                      context:nil];

    CGSize stringSize = frame.size;
    return stringSize;
}

Set the CGSize returned from here as your label frame size.

Upvotes: 1

iPatel
iPatel

Reputation: 47069

For set dynamic frame UILabel use following method

-(void) setDynamicHeightOfLabel:(UILabel *) myLabel withLblWidth:(CGFloat) width andFontSize:(int) fontSize
{
    CGSize myLabelSize = CGSizeMake(width, FLT_MAX);
    CGSize expecteingmyLabelSize = [myLabel.text sizeWithFont:myLabel.font constrainedToSize:myLabelSize lineBreakMode:myLabel.lineBreakMode];
    CGRect lblFrame = myLabel.frame;
    lblFrame.size.height = expecteingmyLabelSize.height;
    myLabel.frame = lblFrame;
    int addressLine = myLabel.frame.size.height/fontSize;
    myLabel.numberOfLines = addressLine;
}

In the above method you just need to pass your label object, width of your label and font size of text, such like...

[self setDynamicHeightOfLabel:lblName withLblWidth:passWidth andFontSize:19];

Upvotes: 1

Tarun Khosla
Tarun Khosla

Reputation: 96

You need to increase the height of UILabel. Just use following method to get the height of uilabel text and then set number of lines as following:

- (CGSize)calculateRowHeightAndWidth:(NSString *)text font:(UIFont *)font width:(CGFloat)width
{
    CGSize size = [text sizeWithFont:font constrainedToSize:CGSizeMake(width, 9999)
                       lineBreakMode:UILineBreakModeWordWrap];
    return size;
}

    textDetailLabel.numberOfLines = size.height/height size of font.0;

Upvotes: 0

Related Questions